6

I am trying to validate a text input when it loses focus. I would like to know which row of the table it is in. This is what I have so far and it keeps coming back as undefined. Any ideas?

$("div#step-2 fieldset table tbody tr td input").blur(function() {
    var tableRow = $(this).parent().parent();
    if ($.trim($(this).val()) == "") {
        $(this).addClass("invalid");
        alert(tableRow.rowIndex);
        $(this).val("");
    } else {
        $(this).removeClass("invalid");
        checkTextChanges();
    }
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jon
  • 5,956
  • 10
  • 39
  • 40

4 Answers4

14

rowIndex is a DOM property, not a jQuery method, so you have to call it on the underlying DOM object:

tableRow[0].rowIndex

or just:

var row= this.parentNode.parentNode;
alert(row.rowIndex);

since you aren't really using jQuery for much there.

In jQuery 1.4 there is $(row).index(), but it scans siblings to find out which child element number it is in its parent. This is slower and will return a different result to rowIndex in the case where you have multiple <tbody>​s.

bobince
  • 528,062
  • 107
  • 651
  • 834
2

With jQuery 1.4.* you can use the index() method.

Your selector is a little more specific then it needs to be. Also you should use the closest method rather then multiple parent() calls. Also cache $(this).

$("#step-2 fieldset table td input").blur(function() {
    var that = $(this),
        tableRow = that.closest('tr');
    if ($.trim(that.val()) == "") {
        that.addClass("invalid");
        alert(tableRow.index());
        that.val("");
    } else {
        that.removeClass("invalid");
        checkTextChanges();
    }
});

Also alert is not a very good debugging tool, might be time for you to check out firebug

PetersenDidIt
  • 25,562
  • 3
  • 67
  • 72
  • Thanks for all of your suggestions! I'm not using 1.4.* so I did not have access to the index() method, I have however implemented the rest of your suggestions +1 – Jon Mar 30 '10 at 13:54
1

You are trying to use the DOM Core attribute on the jQuery object. Try this:

alert(tableRow[0].rowIndex);

@jandreas: from the W3C docs: rowIndex of type long, readonly, modified in DOM Level 2 This is in logical order and not in document order. The rowIndex does take into account sections (THEAD, TFOOT, or TBODY) within the table, placing THEAD rows first in the index, followed by TBODY rows, followed by TFOOT rows.

.index() would not take those THEAD etc. into account.

janmoesen
  • 7,910
  • 1
  • 23
  • 19
0

try closest('tr') if you are version 1.3+ . it'll work better than parent().parent()

easement
  • 6,119
  • 3
  • 29
  • 36