Reputation: 1705
I have very simple and clear question. i have dynamically created input fields with:
id=pend_1, id=pend_2 .....id=pend_14
i need to get Sum() of all the input fields which id starts from pend_* ?
for more clarity, please see the figure:
is there any easiest way to get sum() of all the input fields?
In this scenario, users will put values in the text fields and jquery will calculate the sum() with onBlur() event...
Upvotes: 1
Views: 2720
Reputation: 555
Let's assume there are number of Divs with id="test_1", id="test_2"
etc..., you can get the count using the following method
var count = ($("div[id^='test']").length
For taking the sum you have to write the Anonymous function which takes the result and element as the parameter As @Rajaprabhu Aravindasamy mentioned the solution is correct,
But a small change if a input type has NaN Value then convert it to 0 here is the code with slight modification., you can use ||
operator in this case to return 0 by default if the value is NaN for eg. let a = $('#a').val() || 0;
var sum = $("input[id^='test'][type='text']")
.get()
.reduce((res, elm) =>
(res + (+elm.value || 0)), 0);
Hope this Helps
Upvotes: 3
Reputation: 2426
$('input[id^="pend_"][type="text"]').on('input',function(){
var sum = 0;
$('input[id^="pend_"][type="text"]').each(function(){
var valu = $(this).val() == '' ? 0 : $(this).val();
if(!isNaN(valu))
{
sum = sum + parseFloat(valu);
}
});
$('label').text(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="pend_1" ><br/>
<input type="text" id="pend_2" ><br/>
<input type="text" id="pend_3" ><br/>
<input type="text" id="pend_4" ><br/>
<input type="text" id="pend_5" ><br/>
Result:<label id="result" value="label"> </label>
Upvotes: 1
Reputation: 127
Better you add single class to all of those fields such as
< input type="text" class="sum_item" id="pend_1" />
< input type="text" class="sum_item" id="pend_2" />
And use following code to sum them up
var sum=0;
$('.sum_item').each(function(){
var item_val=parseFloat($(this).val());
if(isNaN(item_val)){
item_val=0;
}
sum+=item_val;
$('#total').val(sum.toFixed(2));
});
Upvotes: 3
Reputation: 67187
Yes, You can get it by using the following code,
let sum = $("input[id^='pend_'][type='text']").get()
.reduce((res, elm) => (res + (+elm.value)), 0);
use a starts with selector
and then get()
the array representation of the elements, then reduce
it to a sum.
Upvotes: 1
Reputation: 8249
$("[id^=AAA_][id$=_BBB]")
It will return all the elements that matches all the specified attribute filters:
[id^=AAA_] matches elements with id attribute starting with AAA_,
and[id$=_BBB] matches elements with id attribute ending with _BBB.
Hope this helps.
Upvotes: 1