I have a jQuery-based form where you can add extra people to the application. I'm clonin开发者_开发问答g the first fieldset and adding it onto the end up to a max of 3 additional people. When you've added 1 extra person then you have the option to remove that person.
However, my remove button isn't working. It was, earlier, until I added the extra functions to the cloning to change the ids of other elements within the fieldset.
I'm using:
$(".remove").click(function() {
$(this).parent().remove();
which was working originally but now it's not and I can't figure out why.
I've taken out the lines that stop the first 'delete this person' just to show that the first one still works but the rest don't. (I'll be positioning the first one off stage eventually when it's fixed)
Probably easier to see it so I put it up here.
So essentially, any ideas why my 'delete this person' isn't working on everything but the first section?
Try:
$(document).on('click', '.remove', function() {
$(this).parent().remove();
});
Events are bound on page load so newly added element aren't.
The 'live' function call has been deprecated and no longer works. You can find instructions for how to rewrite functions using the replacement 'on()' method here and more info about the deprecation:
http://api.jquery.com/live/
To handle all current and newly created elements, you must now use:
$(document).on("click", ".remove", function() {
$(this).parent().remove();
});
jQuery runs on the document object, not the element and there is an additional parameter to specify which elements to watch and add event listeners to.
Make sure you close your expresion:
$(".remove").click(function() {
$(this).parent().remove();
});
You can do this for delete the parent:
$(document).on("click", ".remove", function() {
$(this).parent().remove();
});
or you can do this for delete all parents:
$(document).on("click", ".remove", function() {
$(this).parents().remove();
});
The elements don't originally exist, which means you need to use .live()
or .delegate()
For example, change:
use $(".remove").click(...)
instead of $(".remove").live("click", ...)
this
精彩评论