Ok, this seems like it should be a simple question, but the answer eludes me. I have a form that is built from JSON data from which I build a table of 3 rows and 14 columns each containing an INPUT text control.
When the value in any of those controls changes I need to find the containing row whose input control in the first column equals a specific year.
Here is a sample of the markup:
<table id="MyTable">
<tr>
<td><input type="text" /></td>
<td><input type="text" class="changeHandled"/></td>
<td><input type="text" class="changeHandled" /></td>
</tr>
</table>
The selector I've tried is: #MyTable tr:has('input[value="{year}"]')
and a few dozen variations.
I replace the {year}
string with the year value I'm searching for, so it ends up looking like: #MyTable tr:has('input[value="2014"]')
I believe it may be due to the fact the values are set through code initially, because if I use #MyTable tr:has('input')
it returns all of the rows.
Because of maintainability I don't want to hardcode the path and just say $(this).closest("tr")...
in javascript code.
Any idea how to retrieve a reference to the TR containing an input with a specific value? If my code is correct, do I need to do something different when setting the value via code?
The selector $('#MyTable tr:has(input[value="2014"])')
will only work if the input
element has a hardcoded value
attribute with a value of 2014
. See this example.
If you are trying to select an input
element without a hardcoded value
attribute, then you could filter over the elements and return input
elements whose value equals 2014
. Depending on your needs, you could listen to the input
or change
event.
Example Here
$('#MyTable input').on('input change', function () {
$tr = $('#MyTable tr input:first').filter(function () {
return this.value === '2014' || $(this).attr('value') === '2014';
}).closest('tr');
});
If you were to use a plan JS solution it might look like:
function getRowByYear(year) {
var table = document.getElementById('MyTable');
var row, rows = table.rows;
var input;
for (var i=0, iLen=rows.length; i<iLen; i++) {
input = rows[i].cells[0].getElementsByTagName('input')[0];
if (input.value == year) {
return rows[i];
}
}
}
and would probably run very much faster than a jQuery selector.
However, since you say "When the value in any of those controls changes…" then perhaps you are using a change event, so you can simply get the input from which the event was dispatched (this within the listener) and go up to the nearest row.
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