Reputation: 77
I am making a table using jquery, where the ids of the tiles are generated using a nested FOR loop. I am trying to add and event listener to the tiles, using their ids, so I can run a function when clicking them. However, the id, stored in the variable boatStatusClient is not recognised, and throws an error. Can anyone see the problem?
for (y_client = 1; y_client < 11; y_client++) {
battlefield_client += "<tr>";
for (x_client = 1; x_client < 11; x_client++) {
battlefield_client += "<td onclick = '' class = 'tile' style='border: 3px solid black;' id=" + "cell_client_" + x_client + "_" + y_client + "><pre> </pre></td>";
boatStatusClient = document.getElementById('cell_client_' + x_client + "_" + y_client);
console.log(boatStatusClient);
boatStatusClient.addEventListener("click", function(){boatGrid.placeBoat_client()});
}
battlefield_client += "</tr>";
}
$(document).ready(function() {
$("#tableGrid_client").html(battlefield_client); //loads table
Upvotes: 0
Views: 65
Reputation: 479
Looks like your trying to find an element with document.getElementById() that does not exist in the DOM.
First append it to the page then search and add the relevant event listenrs.
But, you should really think of doing it with document.createElement (or jQuery objects) instead of concating strings. See this question for a more in-depth discussion.
Upvotes: 2
Reputation: 488
As fistuks already mentioned, you're trying to reach an element that is not yet in the DOM, and therefor you can't get it.
By doing this:
battlefield_client += "<td onclick = '' class = 'tile' style='border: 3px solid black;' id=" + "cell_client_" + x_client + "_" + y_client + "><pre> </pre></td>";
You only make a string that holds this, but you never insert it into the dom - well at least not before you try to get that actual element.
So what you want to do is: append this string to the view/dom :-) Then you should be able to get it with your above method.
Besides that I would consider placing quotes better, and not mix the use of single- and doublequotes. My suggestion would be to always use single quotes when writing JavaScript, and double quotes when writing html.
Upvotes: 0
Reputation: 175
Look, your event function is executing before of the DOM Element be created!
Try this:
for (y_client = 1; y_client < 11; y_client++) {
battlefield_client += "<tr>";
for (x_client = 1; x_client < 11; x_client++) {
battlefield_client += "<td onclick = '' class = 'tile' style='border: 3px solid black;' id=" + "cell_client_" + x_client + "_" + y_client + "><pre> </pre></td>";
}
battlefield_client += "</tr>";
}
$(document).ready(function() {
$("#tableGrid_client").html(battlefield_client); //loads table
$('.tile').click(function() {
boatGrid.placeBoat_client();
});
});
Upvotes: 0