Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 684
Sergiu Avatar asked Feb 12 '26 09:02

Sergiu


2 Answers

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/

like image 165
Alvaro Avatar answered Feb 15 '26 10:02

Alvaro


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
like image 33
Eric Avatar answered Feb 15 '26 12:02

Eric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!