kodlik
kodlik

Reputation: 47

How to corectly bind events in a loop

On a page I have couple of divs, that look like this:

<div class="product-input">
    <input type="hidden" class="hidden-input">
    <input type="text">
    <button class="remove">X</button>
</div>

I'm trying to bind an event to that remove button with this code (simplified):

$('.product-input').each(function() {
    product = $(this);
    product_field = product.find('.hidden-input');

    product.on('click', '.remove', function(event) {
        product_field.val(null);
    });
});

It works perfectly when there is only one "product-input" div. When there is more of them, all remove buttons remove value from the hidden field from the last product-input div.

https://jsfiddle.net/ryzr40yh/

Can somebody help me finding the bug?

Upvotes: 0

Views: 51

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

You need to declare product and product_field as local variables, now they are global variables. So whichever button is clicked inside the click handler product_field will refer to the last input element.

$('.product-input').each(function() {
    var product = $(this);
    var product_field = product.find('.hidden-input');

    product.on('click', '.remove', function(event) {
        product_field.val(null);
    });
});

Demo: Fiddle


But you can simplify it without using a loop as below using the siblings relationship between the clicked button and the input field

$('.product-input .remove').click(function () {
    $(this).siblings('.hidden-input').val('')
})

Demo: Fiddle

Upvotes: 3

Milind Anantwar
Milind Anantwar

Reputation: 82241

You dont need to iterate over the element for binding the same event. you can rather bind the event to all at once:

$('.product-input').on('click', '.remove', function(event) {
   $(this).prevAll('.hidden-input').val("");
});

If the remove buttons are not added dynamically, you will not need event delegation:

$('.remove').click(function(event) {
  $(this).prevAll('.hidden-input').val("");
});

Working Demo

Upvotes: 5

Related Questions