Ben Hathaway
Ben Hathaway

Reputation: 356

Using Jquery to dynamically add an element to my form

I have followed a tutorial and created some html and Jquery which should dynamically add a new element when the add new button is clicked. However i am testing jsfiddle and it isn't working, i have used the exact same code as used in the tutorial. Can anyone see where i am going wrong?

http://jsfiddle.net/pocockn/P5uPQ/1/

$(function() {
        var addDiv = $('#addinput');
        var i = $('#addinput p').size() + 1;

        $('#addNew').live('click', function() {
                $('<p><input type="text" id="p_new" size="40" name="p_new_' + i +'" value="" placeholder="I am New" /><a href="#" id="remNew">Remove</a> </p>').appendTo(addDiv);
                i++;

                return false;
        });

        $('#remNew').live('click', function() { 
                if( i > 2 ) {
                        $(this).parents('p').remove();
                        i--;
                }
                return false;
        });
}); 

Upvotes: 1

Views: 130

Answers (3)

Sergio
Sergio

Reputation: 28845

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.

So you should replace live() with on().

Try this:

$(function () {
    var addDiv = $('#addinput');
    var i = $('#addinput p').size() + 1;

    $('#addNew').on('click', function () {
        $('<p><input type="text" class="p_new" size="40" name="p_new_' + i + '" value="" placeholder="I am New" /><a href="#" class="remNew">Remove</a> </p>').appendTo(addDiv);
        i++;
        return false;
    });
    $(document).on('click','.remNew', function () {
        if (i > 2) {
            $(this).parents('p').remove();
            i--;
        }
        return false;
    });
});

NOTE:

  • keep in mind that ID's must be unique. I changed to class in the code posted here.
  • Because you are adding content dynamically the remNew must use delegation.

Fiddle

Upvotes: 2

Dangerous
Dangerous

Reputation: 4909

You need to change:

$('#addNew').live('click', function() { ...

to:

$('#addNew').on('click', function() { ...

Upvotes: 1

artud2000
artud2000

Reputation: 544

live is deprecated

$(function() {
        var addDiv = $('#addinput');
        var i = $('#addinput p').size() + 1;

        $('#addNew').click(function() {
                $('<p><input type="text" id="p_new" size="40" name="p_new_' + i +'" value="" placeholder="I am New" /><a href="#" id="remNew">Remove</a> </p>').appendTo(addDiv);
                i++;

                return false;
        });
        alert(i);
        $('#remNew').click(function() { 
                if( i > 3 ) {
                        $(this).parents('p').remove();
                        i--;
                }
                return false;
        });
});        

Upvotes: 1

Related Questions