2

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

4
  • Where do you want to add these input values to? Commented Aug 16, 2011 at 7:07
  • I want all input values to be added and stores in another hidden fields for further use Commented Aug 16, 2011 at 7:08
  • Do you want to summarize the values or just concatenate? Commented Aug 16, 2011 at 7:20
  • @KARASZI I want to sum all input values Commented Aug 16, 2011 at 8:33

4 Answers 4

6

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);
Sign up to request clarification or add additional context in comments.

Comments

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

var val_sum = addValues();

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.