I have some divs being created dynamically and I’m using bind/live (tried both, same results) to add a click function. However, it is returning all the divs with the same class.
Example;
I have 3 dynamically generated divs
1
2
3
If I click on 2, the alert method goes to show 1 then 2 then 3. I only need the one clicked. Thanks!
$("#borang_main_form").append('<div class="borang-row" id="'+id+'"><label id="label_'+id+'"></label><input id="textbox_'+id+'" type="text" /></div>').bind("click", function(){alert(id);});
I’ve tried this and it works.
$("#borang_main_form").append('<div class="borang-row" id="'+id+'"><label id="label_'+id+'"></label><input id="textbox_'+id+'" type="text" /></div>').delegate("#" + id, "click", function(){alert(id);});
However it looks a little dirty. Is there a better way to approach something like this?
When you iterate with your loop, you use method chaining, which basically end up adding n number of event bindings to the same parent item (“#borang_main_form”)
In your loop first append the items, then outside the loop add the event listeners to the individual children elements.
In the event handler function $(this) will be mapped as the item that was clicked (the trigger of the event) and through
$(this).attr('id')you will get the id attribute of that element.