0

I'm creating a table dynamically with jQuery, the whole table is built fine but in a anchor tag which contains a click event it takes the same value in every row that matches with the last element in the loop.

for(x in jsonInput) { 
                $("#tabDatos").find('tbody')
                .append($('<tr>')
                    .append($('<td>')
                        .attr('width','10%')
                        .append($('<a>')
                            .attr('href', '#')
                            .text(jsonInput[x].c00)
                            .click(function() {
                                    alert(x)
                                    return false
                             })
                            )

                    )

The above code should send an alert with '0' clicking the anchor tab in the first row, '1' for the second one, etc. instead, all links send an alert with '5' (last value for x because JSON array has 6 elements), any ideas for this behavior?

  • 1
    That is because you are fetching the x value by reference, not by its value—so when you click on the element it will alert the final x value coming out of the loop. You should bind the value instead—check out [closures in JS](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). – Terry Aug 15 '15 at 20:48
  • Yes, I get it, let me check the link, thanks a lot. – Ottoniel Domínguez González Aug 20 '15 at 16:41

0 Answers0