Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve Table Row Index of Current Row

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();
    }
});
like image 409
Jon Avatar asked Mar 30 '10 13:03

Jon


2 Answers

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.

like image 112
bobince Avatar answered Oct 19 '22 23:10

bobince


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

like image 36
PetersenDidIt Avatar answered Oct 20 '22 01:10

PetersenDidIt