问题
I am having a little bit of difficulty understanding how to do this. However here it goes.
There are a bunch of input fields that user can add to.
I need to write a jQuery script without adding anything to the markup of the HTML explicitly.
- Find all elements with a class of
inputAmt
- If user blurs form input field the jQuery script would trigger.
- Add all the value to find the total.
- If user subtracts anything it needs to reflect the total.
Little complicated for me I would appreciate all the help I can get.
回答1:
First lets get all elements with inputAmt
class.
var elements = $('.inputAmt');
now lets create a function that adds their values
function addElementValues(){
var sum = 0;
elements.each(function(){
sum += parseFloat(this.value);
// when this.value is empty or non numeric the parseFloat returns NaN (Not A Number)
// so you might want to do sum += parseFloat(this.value) || 0;
// to ignore the NaN values
});
// do something with the sum value here
// like display it on some element
}
finally lets use this function when any field is blurred
elements.on('blur', addElementValues);
Full working example
var elements = $('.inputAmt');
function addElementValues() {
var sum = 0;
elements.each(function() {
sum += parseFloat(this.value) || 0;
});
// do something with the sum value here
// like display it on some element
$('#total').text( sum );
}
elements.on('blur', addElementValues);
.w70 {
width: 70px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td class="txtr">
<input type="text" class="inputAmt w70" name="something">
</td>
<td class="txtr">
<input type="text" class="inputAmt w70" name="something1">
</td>
<td class="txtr">
<input type="text" class="inputAmt w70" name="something2">
</td>
<td class="txtr">
<input type="text" class="inputAmt w70" name="something3">
</td>
<td class="txtr">
<input type="text" class="inputAmt w70" name="something4">
</td>
</tr>
</tbody>
</table>
<div id="total"></div>
来源:https://stackoverflow.com/questions/29148865/loop-add-to-array-on-blur