Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show Form Field if Drop Down Item is Selected Using jquery

Tags:

jquery

forms

I'm trying to create a dropdown field where if the "Other" item is selected, then a "Please Specify" text box appears. The below works with just one dropdown select field, but as soon as I add the second select field, it no longer works.

Here's what I have that doesn't seem to work:

CSS...

#techother{display:none;}
#lmsother{display:none;}

Body...

<p>Chose Your Browser: <select name = "Browser" required>
        <option value = "">-- Select an Option --</option>
        <option value = "1">IE</option>
        <option value = "2">FF</option>
        <option value = "3">Safari</option>
        <option value = "4">Opera</option>
        <option value = "5">Other</option>
        </select>
    </p>
  <div id="browserother">
    <p>Please Specify: <label id="browserlabel"><input name="Other Browser" type="text" placeholder="Other Browser" size="50" /></label></p>
    </div>

    <p>Operating System: <select name = "OS" required>
        <option value = "">-- Select an Option --</option>
        <option value = "Win">Windows</option>
        <option value = "ios">iOS</option>
        <option value = "otheros">Other</option>
        </select>
    </p>
  <div id="osother">
    <p>Please Specify: <label id="oslabel"><input name="Other OS" type="text" placeholder="Other OS" size="50" /></label></p>
  </div>

Script...

  <script>
$('form select[name=Browser]').change(function(){
  if ($('form select option:selected').val() == '5'){
    $('#browserother').show();
  }else{
    $('#browserother').hide();
  }
});

$('form select[name=OS]').change(function(){
  if ($('form select option:selected').val() == 'otheros'){
    $('#osother').show();
  }else{
    $('#osother').hide();
  }
});
</script>

Any way to make this work? Thanks!

like image 910
rivitzs Avatar asked Dec 08 '22 13:12

rivitzs


2 Answers

Try this DEMO: http://jsfiddle.net/2pM3n/1/

$('select[name=Browser]').change(function () {
    if ($(this).val() == '5') {
        $('#browserother').show();
    } else {
        $('#browserother').hide();
    }
});

$('select[name=OS]').change(function () {
    if ($(this).val() == 'otheros') {
        $('#osother').show();
    } else {
        $('#osother').hide();
    }
});
like image 150
David Avatar answered Mar 03 '23 22:03

David


There you go: http://jsfiddle.net/ecZrE/

You mixed up some things in the selectors. Use

$('p select[name=Browser]')

instead of

$('form select[name=Browser]')

since there is no form element. But your snippet is incomplete anyway.

Another wrong selector is

$('form select option:selected') 

because you forgot to specify the select element.

like image 40
Alex Avatar answered Mar 03 '23 21:03

Alex