1

I've got a looped click function in my application something similar to

for(var i = 0; i < 10; i++)
{
    $("#clickedButton"+i+"").click(function()
    {
        //Code Here
    }
}

My issue is that I need a way to tell which button is clicked. I could just create 9 click functions but they all do the exact same thing so I figured looping it would be best. Is there a way I can tell which one is clicked. I have been able to successfully do this once like shown below

var i = 0;
if(i == 0)
{
    alert(i);
    $("#amount0").empty();
    amountCount[0]--;
    $("#amount0").append(amountCount[0]);
}
i++

When I try to add on a second if statement when it loops through on the click it changes the information in the first if statement as well. I need to be able to individually change the information and the buttons can be clicked multiple times in any order.

If any other information is needed let me know

John
  • 115
  • 10
  • Please read [ask]. Pay attention to the section about MCVE. Than do that. good luck. – Amit Aug 03 '15 at 23:02
  • I can't fully understand what you want to achieve, have you an example ? – Zakaria Acharki Aug 03 '15 at 23:03
  • Take a look at [Assign click handlers in for loop](http://stackoverflow.com/questions/4091765/assign-click-handlers-in-for-loop) that may help. – Zakaria Acharki Aug 03 '15 at 23:10
  • No need for this loop in the first place, show associated html sample. This should be easily achieved using class and one click handler or an attribute selector for id – charlietfl Aug 03 '15 at 23:14
  • You should take a look at [event bubbling and capturing](http://javascript.info/tutorial/bubbling-and-capturing). – yvesmancera Aug 03 '15 at 23:17

2 Answers2

2

Try this:

for(var i = 0; i < 10; i++)
{
    $("#clickedButton"+i+"").click(function()
    {
        alert("You have clicked: ", $(this).attr('id'));            
    }
}
missimer
  • 4,022
  • 1
  • 19
  • 33
Repo
  • 1,736
  • 1
  • 10
  • 6
  • I completely forgot about using `this`. Haven't been able to fully test it out but if it works I'll accept it as the answer – John Aug 03 '15 at 23:50
0

Since you are assigning an id to each of the buttons that is pretty much identical except for the index at the end of the id, you could give all the buttons the same class and use the data- or id attribute for what index they represent.

HTML

<button class="myButton" data-index="0" />
<button class="myButton" data-index="1" />
...

JAVASCRIPT

$(".myButton").click(function () {
    var idx = $(this).attr("data-index");
    // You can now use the index of this button
    // where ever you need it
});
SaoBiz
  • 1,249
  • 15
  • 16