mymotherland
mymotherland

Reputation: 8228

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_" ?

Upvotes: 2

Views: 4900

Answers (4)

Mak
Mak

Reputation: 20453

Maybe this (http://jsfiddle.net/3AW7j/) code will help

Upvotes: 0

KARASZI Istv&#225;n
KARASZI Istv&#225;n

Reputation: 31467

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 ,.

Upvotes: 0

32423hjh32423
32423hjh32423

Reputation: 3088

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);

Upvotes: 6

Paul
Paul

Reputation: 141839

function addValues(){
    var v = 0;
    $("input[id^='test_']").each(function(i, el){
        v += parseInt(el.value, 10);
    });
    return v;
}

var val_sum = addValues();

Upvotes: 1

Related Questions