Reputation: 356
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
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:
remNew
must use delegation.Upvotes: 2
Reputation: 4909
You need to change:
$('#addNew').live('click', function() { ...
to:
$('#addNew').on('click', function() { ...
Upvotes: 1
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