How Can I Get A Value From The Nth Element Of The Closest 'tr'?
Solution 1:
In your code, row.find(':nth-child(1)')
selects a <td>
element -- the first child of the <tr>
. But it seems that you want to select <input>
elements in each row to get their values.
In my example, below, I've given each input a class that identifies it as a "quantity", "price", or "total" field. I find the closest row to the current <input>
. Then I find the value for each input within that row, calculate the total, and set the value of the "total" <input>
to that number.
I'm using jQuery's selector context, which is internally equivalent to find()
.
$('input.value').keyup(function() {
var $row = $(this).closest('tr');
$output = jQuery('input.total', $row),
quantity = jQuery('input.quantity', $row).val(),
price = jQuery('input.price', $row).val(),
total = quantity * price;
$output.val(total);
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><table><tr><td><inputtype="text"class="value quantity" /></td><td><inputtype="text"class="value price" /></td><td><inputtype="text"class="total" /></td></tr><tr><td><inputtype="text"class="value quantity" /></td><td><inputtype="text"class="value price" /></td><td><inputtype="text"class="total" /></td></tr><tr><td><inputtype="text"class="value quantity" /></td><td><inputtype="text"class="value price" /></td><td><inputtype="text"class="total" /></td></tr></table>
You can use nth-child
selectors rather than classes, if you prefer. But remember that "nth" children are the <td>
elements, not the <input>
elements. You'll need to select the <input>
within each "nth" <td>
child. Something like:
$row.find('td:nth-child(1) input').val()
See the example below:
$('input.value').keyup(function() {
var $row = $(this).closest('tr');
$output = $row.find('td:nth-child(3) input'),
quantity = $row.find('td:nth-child(1) input').val(),
price = $row.find('td:nth-child(2) input').val(),
total = quantity * price;
$output.val(total);
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><table><tr><td><inputtype="text"class="value" /></td><td><inputtype="text"class="value" /></td><td><inputtype="text" /></td></tr><tr><td><inputtype="text"class="value" /></td><td><inputtype="text"class="value" /></td><td><inputtype="text" /></td></tr><tr><td><inputtype="text"class="value" /></td><td><inputtype="text"class="value" /></td><td><inputtype="text" /></td></tr></table>
Solution 2:
jQuery has no value
property....use val()
and assuming selectors are valid it should work
var val1 = row.find(':nth-child(1)').val();
Post a Comment for "How Can I Get A Value From The Nth Element Of The Closest 'tr'?"