jin cheng teo
jin cheng teo

Reputation: 305

jquery event handlers within a loop

I currently use javascript to create a html table.

When the user clicks on a button. It appends a tr to the table.

Inside the tr I also append a select2 <select> element.

The id of the select element is accompanied by a number that increments.

So the select element on the first row has an id of item-project-no-0 and the element on the second row has an id of item-project-no-1. So on and so forth.

But now, I need to register the event listener for all the select elements in that table which is dynamically generated. Something like this:

    $('#item-project-no-' + x).on('select2:select', function (e) {

    });

I wanted to tried using a for loop. But I don't think the for loop knows how many times it must loop since the number of select elements is dependent on the number of timer user clicks a button. I need to identify the individual select element that fires an event handle it accordingly.

I am open to all opinions and advice. Thanks.

Upvotes: 1

Views: 75

Answers (2)

gforce301
gforce301

Reputation: 2984

Why not just give each selector a class? Then you can do this:

$(document).on("select2:select", ".mySelectorClass", function() {
  // $(this) is the element
}

This works even for dynamically created elements later.

Upvotes: 2

ferhado
ferhado

Reputation: 2604

Try this example:

$(document).on("select2:select","[id^='item-project-no-']",function() {
  //do somthing
}

Upvotes: 1

Related Questions