Add input text when option selected

安稳与你 提交于 2019-12-23 19:33:33

问题


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?


回答1:


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/




回答2:


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



回答3:


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();
    }
});


来源:https://stackoverflow.com/questions/17420788/add-input-text-when-option-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!