I have a table produced dynamically with each row producing something like this:
<tr name="0">
<td style="text-align:left;">January</td>
<td><input type="text" name="LIB1" value="0" class="oneInput row0" /></td>
<td><input type="text" name="RPI1" value="0" class="oneInput row0" /></td>
<td><input type="text" name="LMM1" value="0" class="oneInput row0" /></td>
<td><b><span class="screenOneTotal">0</span></b></td>
</tr>
I need to put the total of each input in the row in the last column when a value is input. Therefore, I placed this function in the document.ready function
$(".oneInput").live('blur', function(){
var rowID = $(this).parent().parent().attr( 'name' );
var thisLIB = $("input[name=LIB + rowID]" ).val();
var thisRPI = $("input[name=RPI + rowID]").val();
var thisLMM = $("input[name=LMM + rowID]").val();
var rowTotal = parseFloat(thisLIB) + parseFloat(thisRPI) + parseFloat(thisLMM);
$(this).parent().parent().find( 'span.screenOneTotal').empty().html( parseFloat(rowTotal) );
});
Despite the fact that I am explicitly casting each value to a float, the value inserted into the last column is “NaN”.
I think you’re overcomplicating things (and undercomplicating them at the same time). Your over-complication is that you’re looking for three specific things and treating them individually when you could just grab everything that fits a certain pattern and treat them as a group. Your under-complication is that you’re not considering failure conditions from
parseFloatand the odd (until you’re used to it) behavior of NaN.I think you’d be better off going up the DOM to find the containing
<tr>and the iterating through all the.oneInputelements in that row, then you can use one small chunk of code to convert the string values to sensible numbers the same way:The
closestcall will go up the DOM to find the containing<tr>, then thefindwill get all the<input>elements in that row that have a class ofoneInput, then loop over those witheach, extract each value straight from the<input>DOM element withparseFloat, and add them to a running total inrowTotalifparseFloatfinds a number (andisNaNis the what you want to check ifparseFloathanded you a NaN).Something like this: http://jsfiddle.net/ambiguous/DBQL3/