Search code examples
jquerycells

How do I get the current cell in a table using jQuery?


So I'm trying to create a live-updating table using HTML and jQuery. Each row contains expenses, and each cell in the row has a specific formula attached to it. If the user edits any of the cells in a row, then the others in that row will reflect the change.

Example:

[Cell 1] [Cell 2] [Cell 3]

[Cell 1] = 1;
[Cell 2] = [Cell 1] * 2
[Cell 3] = [Cell 1] * 12

I'd love it if the table updated on blur or on keyup, but I don't know how to get the current cell, and update the other cells in that particular row. Basically, I would have a check to see WHICH cell in the row was edited, and update the others accordingly.

if(cell1 was updated) { update cell2, cell3 }

else if(cell2 was updated) { update cell1, cell3 }

else if(cell3 was updated) { update cell1, cell2 }

I tried this to grab the ID of the current cell, and use that to grab the value of another cell in that row. Didn't work:

var id;

$(".moneyTable input").focus(function () {
             id = this;
        });

$('.moneyTable input').blur(function() {
            calculateRow(id);
        });

function calculateRow(id) {
        var a = $(id).closest('tr').children('td:eq(2)').text();
        alert(a);
    }

Solution

  • "I don't know how to get the current cell, and update the other cells in that particular row"

    When your event handler is called this will be a reference to the element in question, so from there you can figure out which row it belongs to:

    $('.moneyTable input').blur(function() {
        var $thisInput = $(this),
            $thisTD = $thisInput.parent(), // or $thisInput.closest("td")
            $thisTR = $thisInput.closest("tr"),
            $otherCells = $thisTR.find("input").not(this); // and so forth
    });
    

    As far as checking whether the clicked cell was cell 1, 2 or 3, there are a few ways to do it. One would be give them classes class="cell1" and so forth, then do:

    if($thisInput.hasClass("cell1")) {
        // do something
    

    Or check the .index() of the parent td within the row:

    if($thisTD.index() === 1) {
        // second cell (zero-based indexes)