Add input text when option selected

2019-07-04 22:54发布

How can I add an an <input type="text"> when a specific option between <select></select> tags is selected, then, if another option is selected, delete that text field using jQuery?

3条回答
叛逆
2楼-- · 2019-07-04 23:43

If you want to display a then add it where you want and set it to display none and then get it from JQuery

<select id="mylist">
    <option selected></option>
    <option value="1" >aaaa</option>
     <option value="2">bbb</option>
    <option value="3">ccc</option>
</select>
<input id="id" type="text" style="display:none;" />

then into your JS

$('#mylist').change(function(){
    if( $(this).val() == '1'){
        $('#id').show();
    }else{
        $('#id').hide();
    }
});
查看更多
神经病院院长
3楼-- · 2019-07-04 23:45

To get the value of a <select>, use the .val() method. To add/remove an element, there are several options. I will give you one of them example:

$('<input type="text" />').appendTo('body'); // Will append this element to <body>
$('input').remove(); // Removes this item from the document
查看更多
趁早两清
4楼-- · 2019-07-04 23:48

You should make use of change event. Then you could compare the value for which you want to create the input and add it to the body or to any other element.

Living example: http://jsfiddle.net/MKPdb/

Having a list like this, with the id mylist, for example:

<select id="mylist">
 ...
</select>

You could use this:

$('#mylist').change(function(){
    if( $(this).val() == '1'){
        $('body').append('<input id="myInput" type="text" />');
    }else{
        $('#myInput').remove();
    }
});

Living example: http://jsfiddle.net/MKPdb/

查看更多
登录 后发表回答