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();
}
});
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With