Harshul Sahni
Harshul Sahni

Reputation: 140

Not choosing correct table cell on table click

I am trying to build a table where, on click, an X will appear on the cell that was clicked. Here is my JSFiddle. Unfortunately, the program always chooses the first cell in my table. What am I doing wrong here?

jQuery:

function addltr ()
{
    var data = "#" + $('#board td').attr('id');
    alert (data);
    $(data).html("X");           
}
$(document).ready(function(){
    $("#board td").click(function() {
        addltr();
    });
});

Thanks

Upvotes: 0

Views: 14

Answers (2)

Tomas K
Tomas K

Reputation: 371

I have updated your jsfiddle : http://jsfiddle.net/67cmjL57/1/

Simply just pass the element via

Event.target.id

Working code:

  function addltr (name){
   var data = "#" + name;
   alert (data);
   $(data).html("X");           
  }

$(document).ready(function(){
    $("#board").click(function(event) {
        addltr(event.target.id);
    });
});

Upvotes: 1

SuperVeetz
SuperVeetz

Reputation: 2136

Here's one way you could do it: I added a class each time a cell was clicked, and inserted the HTML alittle differently. Then i check that the td doesn't have the class clicked to ensure that only 1 X is created for each td.

Updated JS Fiddle

Upvotes: 1

Related Questions