Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Add/Remove textbox and corresponding delete button

How can I dynamically add/remove textbox (not clearing the data of textbox) and corresponding delete button on corresponding delete button click event through javascript?

NOTE:There is separate button for every dynamically created textbox.

Below is my javascript function. I'm using jQuery 1.3.2

function addOption()
{
        var d=document.getElementById("yash");
        d.innerHTML+="<input type='text' id='mytextbox' name='textbox' class='form-field medium' >";
        d.innerHTML+="<input type='button' id='mybutton' name='del'>";      
        $("#mybutton").click(function () {
            $("#mytextbox").remove();
            $(this).remove();
        });
        d.innerHTML+="<br/>";

}
like image 223
Yash Avatar asked Feb 24 '23 01:02

Yash


1 Answers

I made a very simple example for you: http://jsfiddle.net/BHdhw/

You can change it to suite your needs, here is the code:

HTML

<div class='Option'><input type='text' name='txtTest'/> <span class='Delete'>Delete</span></div>

<br/><br/>
<span class='Add'>Add Option</span>

Jquery

$(function(){

    $('.Delete').live('click',function(e){
    $(this).parent().remove();
    });
    $('.Add').live('click',function(e){
        $('.Option:last').after($('.Option:first').clone());
    });

});

NOTE : When working with dynamic HTML, always use .live to bind your events

UPDATE [Retrieving all values]

Link example how to retrieve values: http://jsfiddle.net/BHdhw/1/

Added HTML

<span class='Retrieve'>Retrieve Values</span>

Added Jquery

$('.Retrieve').live('click',function(e){
        $('.Option input').each(function(i,e){
        alert($(e).val()); //Alerts all values individually
        });
});
like image 70
Marc Uberstein Avatar answered Feb 25 '23 18:02

Marc Uberstein