Home > database >  HTML form show/hide options using JavaScript
HTML form show/hide options using JavaScript

Time:10-28

I am attempting to use JavaScript to show/hide specific advanced fields in a HTML form. I am using the example from Hide/show advanced option using JavaScript which looks to be working well and I am able to hide the input marked with the correct div ID. However each of my inputs use their own div (and I would like to keep it this way if possible) which causes the JS to play up.

HTML:

    <div >
      <label for="text-c578" >Template Frequency (seconds)</label>
      <input type="text" placeholder="Template Frequency" id="text-c578" name="number-1" >
    </div>
    <div id='test' >
      <label for="text-16e6" >Source IP Address</label>
      <input type="text" placeholder="Source IP Address" id="text-16e6" name="text" >
    </div>


    <div id='advancedOptions' >
      <label for="text-c9f3" >Destination IP Address</label>
      <input type="text" placeholder="Destination IP Address" id="text-c9f3" name="text-2" >
    </div>
    <div >
      <input type="submit" value="submit" >
      <a href="#" >Submit</a>
    </div>
  </form>
</div>
<a href="#" > </a>

JavaScript:

    <script type='text/javascript'>
    $(document).ready(function () {
        $('#advancedOptions').hide();
        $('.u-btn-2').click(function() {
            if ($('#advancedOptions').is(':hidden')) {
                 $('#advancedOptions').slideDown();
            } else {
                 $('#advancedOptions').slideUp();
            }
        });
    });
</script>

Currently I am able to hide the input with div id='advancedOptions' however I would like to also apply this to div id='test'. I tried modifying the JavaScript to the below but this didn't work (it hides id='test' and doesn't look to apply to div id='advancedOptions':

            <script type='text/javascript'>
    $(document).ready(function () {
        $('#advancedOptions' && '#test').hide();
        $('.u-btn-2').click(function() {
            if ($('#advancedOptions' && '#test').is(':hidden')) {
                 $('#advancedOptions' && '#test').slideDown();
            } else {
                 $('#advancedOptions' && '#test').slideUp();
            }
        });
    });
</script>

Is there a way I can modify this JavaScript to apply to multiple div ID's as I am planning on adding more form inputs in the future?

I am a novice with Java so any help would be great, thanks!

CodePudding user response:

You pass a wrong param in this line

$('#advancedOptions' && '#test').hide()

So '#advancedOptions' && '#test' returns '#test'

(See more abot logical AND operator here)

You can write this function in 2 lines

$('#advancedOptions' && '#test').hide()

So the line above turns into

$('#advancedOptions').hide()
$('#test').hide()
  • Related