My goal is to create a clickable grid in jQuery/javascript that when a cell is clicked it will return the index value of the cell and then not allow for anymore clicking after the first click (I'm working on a board game so a click on the board would be a move and once you have moved you can't move until your next turn). However, currently I'm having issues simply getting my click event to work properly.
For now I'm just looking to make it so when I click on my grid it changes the color of the cell to red.
I looked at Creating a Clickable Grid in a Web Browser but I have very little experience with js so I was fairly confused by how the callback functions worked. Therefore I was attempting to use part of that example and jQuery which seems, at least to me, to be much more understandable when it comes to attaching events to things.
EDIT: Forgot to say what my issue was but its the fact that when I run all of the following code and click on the grid nothing happens.
grid.js:
$(document).ready(function()
{
grid();
});
$("#grid td").click(function()
{
alert("Clicked!");
$("#grid td").addClass("clicked");
});
function grid()
{
var grid = document.getElementById("grid");
for(var r = 0; r<18; r++)
{
var tr = grid.appendChild(document.createElement('tr'));
for(var c = 0; c<18; c++)
{
var cell = tr.appendChild(document.createElement('td'));
}
}
}
grid.css:
.grid { margin:1em auto; border-collapse:collapse }
.grid td {
cursor:pointer;
width:30px; height:30px;
border:1px dotted #ccc;
text-align:center;
font-family:sans-serif; font-size:16px
}
.grid td.clicked {
background-color:red;
}
test.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="grid.css" rel="stylesheet">
<script src="grid.js"></script>
</head>
<body>
<table class="grid" id="grid">
</table>
</body>
</html>