views:

124

answers:

5

Hi Everyone,

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();
    }
});
A: 

with jQuery 1.4+ try tableRow.index() instead.

Kind Regards --Andy

jAndy
A: 

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
A: 

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

easement
A: 

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
+1  A: 

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
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