I have a group of spinners <select>
input fields and I want to find the sum of them live. I figured the easiest way would be to use jquery's class selector but it does not store the .val()
's of elements of a similar class in an array.
Is there a way to store all the values of a bunch of <select>
开发者_运维知识库 Inputs in an array so I can find the sum of all of their values.
My not working code looks like this.
function calcPrice() {
var price = $('.food').val() || [];
}
$("select").change(calcPrice);
This might be overkill, but you could use http://www.pengoworks.com/workshop/jquery/calculation/calculation.plugin.htm
or you could simply do:
var price = 0.0
$(".food'").each(function() {
price += +this.value
});
Would you mind to clarify what are the .food
elements? Are they input fields? Otherwise, you may want to try using $('.food').text()
instead.
Similar to btiernay's answer, but if you wanted to keep the actual array you can do:
var prices = $.map($(".food"), function () {
return +this.value;
});
var expenses = 0.0;
$(".expense").each(function() {
expenses += +this.value;
});
$("#expense-total").html(expenses);
Basically the same as btiernay but it has missing ; which could fool noobs. Also added jquery element example to push the final value to a sum field. Sorry I could't add as a comment as I rarely post so reputattion less than 50.
Live example under business expeses here: http://contractor.icalculator.info/calculator/PAYE-calculator.html
精彩评论