Sergiu
Sergiu

Reputation: 355

Add input text when option selected

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?

Upvotes: 3

Views: 16645

Answers (3)

user2166307
user2166307

Reputation:

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

Upvotes: 0

Alvaro
Alvaro

Reputation: 41595

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/

Upvotes: 3

Eric
Eric

Reputation: 18912

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

Upvotes: 2

Related Questions