Skip to content Skip to sidebar Skip to footer

Selecting An Adjacent Td In A Table Grid With Jquery

I'm trying to make a simple numbers games using jQuery. I built a 7x7 grid using an html table. I created some jQuery functions to allow the user to highlight and un-highlight cell

Solution 1:

Picking up the table from your website, I would change it a bit adding classes

<table><trclass="row"><tdclass="square candidate"></td><tdclass="square"></td><tdclass="square"></td><tdclass="square"></td><tdclass="square"></td><tdclass="square"></td><tdclass="square"></td></tr>
    ...
</table>

CSS:

.square {
    width: 30px;
    height: 30px;
    border: white solid 1px;
    background-color: lightblue;
}

.highlighted {
    background-color: lime;
}

and then select adjacent squares

$('.square').click(function () {
    if ($(this).hasClass('candidate')) {
        $(this).addClass('highlighted');
        // select adjacent squares// horizontal
        $(this).prev('.square').addClass('candidate');
        $(this).next('.square').addClass('candidate');
        // verticalvar i = $(this).index();
        $(this).parent('.row').prev('.row').children(':eq(' + i + ')').addClass('candidate');
        $(this).parent('.row').next('.row').children(':eq(' + i + ')').addClass('candidate');
    }
});

A square is a .candidate, if it is adjacent to an already .highlighted square.

Solution 2:

jQuery's .index() functionality can solve this for you. It can tell you which item is selected in a group of items.

http://api.jquery.com/index/

Solution 3:

Assign each cell an x and y coordinate. Also, add a class "selected" do any div that gets highlighted. For example.

<div data-x="1"data-y="1"><div data-x="2"data-y="1">
<div data-x="1"data-y="2"><div data-x="2"data-y="2">

Then something such as the following.

var div = $('#idOfDivJustClicked');
var x = div.data('x');
var y = div.data('y');

Then search for divs using jquery's attr selector that contain an x or y coordinate that are plus or minus one. This is not the exact logic, you would need to implement something similar.

if ($('div[data-x=' + (x+1) + '][data-y=' + y + ']').hasClass('selected'))
{
    // found an adjacent highlighted cell// execute code
}

Post a Comment for "Selecting An Adjacent Td In A Table Grid With Jquery"