How to add all input values using jquery
I have the dynamically generated input values in my project. I need to get all the values which has similar id's like "test_1
".
<input type="hidden" id="test_1" value="1">
....
<input type="hidden" id="test_10" value="10">
So here i can use $("input[id^='test_']")
to find all input values. IS there any logic to ADD all input values which has id开发者_如何学编程 "test_" ?
If you mean get the sum of the input values that start test_ then try this
val = 0;
$("input[id^='test_']").each(function() {
val = $(this).attr('value') + val;
});
console.log(val);
function addValues(){
var v = 0;
$("input[id^='test_']").each(function(i, el){
v += parseInt(el.value, 10);
});
return v;
}
var val_sum = addValues();
This could do it:
$("input#all").val($.map($("input[id^='test_']"), function( item ) {
return $(item).val();
}).join(","));
With this the <input id="all" type="hidden"/>
item will have all the values separated by ,
.
Maybe this (http://jsfiddle.net/3AW7j/) code will help
精彩评论