jQuery checkerBoard board sizing

I'm trying to create a jQuery CheckerBoard, I have this much so far, everything seems to work fine, but everything I enter a new number, it appends on to the existing checkerboard, how to I edit my code so that everytime I input a new number into the input box, the board changes to that size and doesn't append on to it, here is what I have gotten so far, I'm told that there are two reasons for this that it keeps growing instead of resetting, first is that var checkerBoard = []; is stored on the global scope, it pushes more checker squares into the array, and that to overwrite the previous content, I need to use .html(), though not should sure how it should be done, please help


Game Board

<table id="gameBoard">


var checkerBoard = [];
var function1 = function(calcs){

for(var i = 0; i < calcs; i++){

var trOdd = $('<tr>').addClass('odd');
var trEven = $('<tr>').addClass('even');

if(calcs % 2 !== 0 && i % 2 !== 0){ checkerBoard.push(trOdd); }
else if(calcs % 2 !== 0 && i % 2 === 0) { checkerBoard.push(trOdd); }
else if(calcs % 2 === 0 && i % 2 !== 0){ checkerBoard.push(trEven); }
else{ checkerBoard.push(trOdd); }

for(var j = 0; j < calcs; j++){
 $( ".odd td:odd" ).css( "background-color", "red" );
 $( ".odd td:even" ).css( "background-color", "black" );
 $( ".even td:odd" ).css( "background-color", "black" );
 $( ".even td:even" ).css( "background-color", "red" );

'border-collapse' : 'collapse',
'border' : 'solid 1px black'
 'width'  : '30px',
'height' : '30px'

var calc = $(this).val();

Answers 1

  • You need to add checkerboard = []; as the first line inside your function1 definition and change $('tbody').append(checkerBoard); to $('tbody').empty().append(checkerBoard);. Though I would recommend moving your checkerboard variable into the function, if possible, so that the variable is recreated each time function1 is called instead of being a global variable that you have to clear.

    The reason you need to reset your checkerboard variable is because currently you are using checkerboard.push(), which will append the new tr to the end of the array and make it so you you have all of your original rows plus the new ones you are adding.

    The reason you need to call .empty() is essentially the same as above. .append() adds the new rows after the existing rows. Calling .empty() will remove the existing rows before adding the new rows.

Related Articles