jQuery Show a Textbox When an Option is Selected

2019-03-28 06:21发布

问题:

I have the following code:

<select>
<option value="Type 1">Type 1</option>
<option value="Type 2">Type 2</option>
<option value="Type 3">Type 3</option>
<option value="Other">Other</option>
</select>

<input type="text" id="other" />

What I want to do is using jQuery make the textbox below hidden by default, and then show it if a user selects the other option from the dropdown.

回答1:

No need for any css here.

$('#sel').change(function() {
    var selected = $(this).val();
    if(selected == 'Other'){
      $('#other').show();
    }
    else{
      $('#other').hide();
    }
});


回答2:

<select id="sel">
<option value="Type 1">Type 1</option>
<option value="Type 2">Type 2</option>
<option value="Type 3">Type 3</option>
<option value="Other">Other</option>
</select>

<input type="text" id="other" style="display: none;" />

$('#sel').change(function() {
    $('#other').css('display', ($(this).val() == 'Other') ? 'block' : 'none');
});


回答3:

Try this:

<select id="selectbox_id">
<option value="Type 1">Type 1</option>
<option value="Type 2">Type 2</option>
<option value="Type 3">Type 3</option>
<option value="Other">Other</option>
</select>

<input type="text" id="other" />

JQuery:

$(function(){
  // hide by default
  $('other').css('display', 'none');

  $('selectbox_id').change(function(){
   if ($(this).val() === 'Other') {
     $('other').css('display', 'block');
   }
 });
});