Show a text field on a specific option select

2019-06-01 10:26发布

I'm trying to learn some jQuery and I can't figure it out, how to show a text field (ID-based of course) when I select a specific option in my select tag. I've Google'd for a answer to my problem, but I haven't find anything yet. There for I'm asking you how I can fix this. See below how I want it.

As default:

Select tag

  • Option 1

  • Option 2

  • Option 3

Text field which is hidden by default.

If I choose Option 1, the text field remains hidden. If I choose Option 2 the result is the same as the first one. If I choose Option 3 the text field will be visible. If I choose another option, say Option 2 back again, the text field will be hidden.

I hope you understand what I mean :)

Thanks in advance.

3条回答
放我归山
2楼-- · 2019-06-01 11:01

Look at this: http://jsfiddle.net/a8ZWx/

You may use the change event of the select element to decide whether to show or hide the text box.

查看更多
劫难
3楼-- · 2019-06-01 11:11
$('#myselect').change(function(){

var val =$("#myselect :selected").val();

if(val == 'Option 3'){
      $('#textbox').show();

}
else{
     $('#textbox').hide();
}

});
查看更多
不美不萌又怎样
4楼-- · 2019-06-01 11:13

jsfiddle Example

Css

.hiddenField{
  display: none;
}

Html:

<select id="myOptions"> 
    <option value="Option 1">Option 1</option>
    <option value="Option 2">Option 2</option>
    <option value="Option 3">Option 3</option>   
</select>
<input type="text" class="hiddenField" id="myTextBox" />

jQuery

$(document).ready(function(){
    $('#myOptions').change(function(){
       $(this).val() == "Option 2" ? $('#myTextBox').show() : $('#myTextBox').hide();
    });
});
查看更多
登录 后发表回答