Add input text when option selected

2019-07-04 23:28发布

问题:

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