Matt Smith
Matt Smith

Reputation: 2120

Get table rows and cells with jQuery

I'm working on a web game and need to check for which cells on the table have been selected by the user. Right now I'm just checking for the row and cell index value:

JavaScript

function checkForWin() {
    var card = document.getElementById('card');
    if ((card.rows[0].cells[0].marker && // 1st row
        card.rows[0].cells[1].marker &&
        card.rows[0].cells[2].marker &&
        card.rows[0].cells[3].marker &&
        card.rows[0].cells[4].marker)) {
        youWin();
    } else {
        noWin();
    }
}

Is there a more elegant of doing this with jQuery?

Upvotes: 0

Views: 138

Answers (2)

dreyescat
dreyescat

Reputation: 13808

Using jQuery you could iterate over the list of marked cells or just get the list of marked cells like this:

var marked = $('#cards td.marked');
// If you have a special way to detect a cell is marked that 
// needs more custom test than checking the class you can use .filter.
// Just as example I use the same condition.
//var marked = $('#cards td').filter(function () {
//    return $(this).hasClass('marked');
//});


// If you want to just iterate the selected cells.
marked.each(function () {
    var i = $(this).closest('tr').index();
    var j = $(this).index();
    console.log(i, j);
});

// If you want to the the array of selected cells.
var indexes = marked.map(function () {
    return {
        i: $(this).closest('tr').index(),
        j: $(this).index()
    };
}).get();

To make it easier I assumed that a cell with the marked class means a marked cell. However you can use the condition you want to get the list of marked cells.

See small demo

Upvotes: 0

BastienSander
BastienSander

Reputation: 1838

Just make some loop :

function checkForWin() {
var card = document.getElementById('card');
var win = true;
for (var i = 0; i < card.rows[0].cells.length; i++){
    if(!card.rows[0].cells[i])
       win = false;
}
if(win)
  youWin();
else
  noWin();
}

Upvotes: 2

Related Questions