Skip to content Skip to sidebar Skip to footer

Jquery .remove() Not Working For Dynamic Form

I am creating a dynamic form that allows a user to add/remove text fields. While I can add text fields with no problem, I'm having difficulty removing specific text fields. Wheneve

Solution 1:

Instead of this:

$( ".remove" ).on( "click", function(event) {

Try this:

$(document).on("click", ".remove", function(event) {

Solution 2:

Try this:

$( "body" ).on( "click", ".remove", function(event) {
      event.preventDefault();                 
      $(this).closest(".form-group").remove();
});

basically you can put any parent of the class remove (which is not dynamically generated) instead of body.

Solution 3:

With this:

$(document).ready(function() {
 $( ".remove" ).on( "click", function(event) {
                event.preventDefault();                 
                $(this).closest(".form-group").remove();
            });
}

you are binding the listener to the click event on the "remove" item present on the page at load time.

Every other item added after that time will be without any binded listener.

You should either use the event delegation using the 3 parameters listener

$(document).ready(function() {
 $( "form" ).on( "click", ".remove" ,function(event) {
                event.preventDefault();                 
                $(this).closest(".form-group").remove();
            });
}

The semantic of this declaration consist in binding the event on the full form (which exist at load time), but the event will propagate to the clicked .remove anchor.

If you are using a version of jquery older then 1.7, use delegate

The propagation, or the bubbling, of the events in javascript allow this behaviour.

Post a Comment for "Jquery .remove() Not Working For Dynamic Form"