0

I have this underscore template to add and delete row :

<#
  jQuery( document ).ready( function() {
   jQuery( '.add-ingr' ).click( function() {
    jQuery( '#re-ingr .ingr' ).append( '<div><input 
     type="text" name="ingr[]" value=""/><a href="#" 
     class="remove_field" style="margin-left:10px;">Remove</a><div>');
       });
    jQuery( '.remove_field' ).on("click", function(e){ 
      e.preventDefault(); jQuery(this).parent('div').remove();
       });
      });
        #>

the add row with remove link works , it generates the good html output:

   <div><input type="text" name="ingredients[]" value=""><a href="#" 
   class="remove_field" style="margin-left:10px;">Remove</a><div></div> 
   </div>

But not the remove , nothing happen when i click on the remove hyperlink Any idea pls

1

This isn't WP related but Its not working because you are trying to add an event to a dynamically created element.

Replace...

jQuery( '.remove_field' ).on("click", function(e){ 
    e.preventDefault(); jQuery(this).parent('div').remove();
});

With

jQuery( 'body' ).on("click", '.remove_field', function(e){ 
    e.preventDefault(); jQuery(this).parent('div').remove();
});

You can read more about your issue here.

0

The div's you are trying to bind that event to don't exist when you create the listener. you need to use jQuery event delegation for this. like so:

jQuery( 'body' ).on("click", '.remove_field', function(e){
    e.preventDefault(); jQuery(this).parent('div').remove();
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.