I have an HTML table with input elements that I am using for batch editing. I have constructed a skelton html example below. Could someone please help me figure out how to do something like the following:
- add a selector to each of the “Quantity” fields, e.g. .change()
- get the value in the Quantity and Amount fields, e.g. .val()
- update the Total field, e.g. .text()
The main challenge is that the HTML is generated by my View in my ASP.Net MVC application, and the naming convention for the input id is “objectName_indexNumber_propertName” — e.g. MyObject_1_Quantity.
Would I just do a for-loop / .each(), and then do string manimpulation to get the id and do my magic? Is there a better way? Thanks.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// how do I select all of them?
$('#MyObject_1_Quantity').change(DoCalculation);
});
function DoCalculation() {
alert("what should I do here? I need to know the index/row I'm in, and which cell triggered me.");
}
</script>
</head>
<body>
<p>Test jquery Selector</p>
<table>
<tr>
<td>Row 1</td>
<td><input type="text" id="MyObject_1_Quantity" /></td>
<td><input type="text" id="MyObject_1_Rate" /></td>
<td><span id="MyObject_1_Total">$100.00</span></td>
</tr>
<tr>
<td>Row 2</td>
<td><input type="text" id="MyObject_2_Quantity" /></td>
<td><input type="text" id="MyObject_2_Rate" /></td>
<td><span id="MyObject_2_Total">$100.00</span></td>
</tr>
<tr>
<td>Row 3</td>
<td><input type="text" id="MyObject_3_Quantity" /></td>
<td><input type="text" id="MyObject_3_Rate" /></td>
<td><span id="MyObject_3_Total">$100.00</span></td>
</tr>
</table>
</body>
</html>
This places a handler on the 2nd
<td>in each row. Thenthisin the handler will be that input, so you can get the nested input and the adjacent cells to to the calculation, and set the value in the<span>.Example: http://jsfiddle.net/Skjbv/1/
If it isn’t quite so consistent that you can rely on the 2nd cell, then you could change the DOM selection to this, which places the handler directly on the input:
Example: http://jsfiddle.net/Skjbv/3/
These use the
attribute-ends-with-selector[docs] to select the elements with the proper value at the end of the ID attribute.