Reputation: 137
I'm coding a tictactoe game but the code which I'm using to check whether the user is clicking on an empty square or already filled is not working for me please see what mistake I am doing
function startgame(){
var $board=$('#board');
$('div.square').remove();
for(var i=0;i<9;i++)
$board.append($('<div/>').addClass('square').addClass('empty'));
$('div.square.empty').click(function(){
$this=$(this);
if($('div.square.empty').length==0){
displayendmsg();
}
else {
$this.removeClass('empty');
if(currentplayer=="X")
$this.append($('<div><img src="cross.jpg"> </div>').addClass('cross').css('visibility','visible'));
else
$this.append($('<div><img src="circle.jpg"> </div>').addClass('circle').css('visibility','visible'));
flipturn();
}
});
};
Even on clicking already occupied square I'm enterin the handler don know why ?
Upvotes: 2
Views: 371
Reputation: 5764
I put together a little fiddle to get this thing alive. You capture the event only for empty elements (selector: div.square.empty), like this you would only find empty ones, you can't do a test for .empty length inside because this function only reacts on empty elements. Anyway I modified your function like this:
function startgame(){
var $board=$('#board');
$('div.square').remove();
for(var i=0;i<9;i++) {
$board.append($('<div/>').addClass('square empty'));
}
$board.on('click','.square',function() {
var elm = $(this);
if(elm.hasClass('empty')) {
elm.removeClass('empty');
if(player === 'x') {
elm.addClass('x');
player = 'c';
} else {
elm.addClass('c');
player = 'x';
}
}
});
}
Upvotes: 1
Reputation: 1169
Alternatively you can check if that field has text or not.
if($.trim($("handler").text()) == '') //Then it is obviously empty.
Upvotes: 0