2

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 ?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
decoder
  • 137
  • 3
  • 12

2 Answers2

1

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';
            }
        }
    });
}
axel.michel
  • 5,764
  • 1
  • 15
  • 25
  • You don't remove the `empty` class. In your fiddle player `c` is always able to click all squares even the ones already clicked. Add `elm.removeClass('empty');` as last line within your `if(elm.hasClass('empty')) {` to ensure squares are `locked` after they have been clicked. See here: http://jsfiddle.net/7PSwc/1/ – Nope Dec 22 '12 at 09:26
  • yeah I agree with the div.empty.length thing , but what's wrong with this "$('div.square.empty').click(function()" thanks – decoder Dec 22 '12 at 09:34
  • @axel.michel: +1 for a working fiddle. Very nice, looks good. – Nope Dec 22 '12 at 09:40
0

Alternatively you can check if that field has text or not.

if($.trim($("handler").text()) == '') //Then it is obviously empty.