1

I have a div structure like below

    <div id=main">
<input type="hidden" id="people_0_1_0" value="12"/>
<input type="hidden" id="people_0_1_1" value="12"/>
</div>

Now how to add all hidden input values in a variable. Thanks

manishjangir
  • 1,605
  • 6
  • 24
  • 27

6 Answers6

5

Using Jquery's map function

var myArray = $('#main input').map(function(){
   return $(this).val();
}).get();

It will collect all input's values(12 and 12 in this case) to array variable.

See jsfiddle http://jsfiddle.net/GkXUS/1/

If you want to get sum of values you can do the following

var total = 0;
$.each(myArray,function() {
    total += parseInt(this,10);
});
​
Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
  • Quick question about map, what are the benefits of using it over just a selector and an each (in this example)? (obviously less code but is it quicker as well?) – mbx-mbx Mar 29 '12 at 14:01
  • @Magrangs `map` gives you the collection as a result value, whereas with an `each` you would have to init the collection outside the each-callback and add to it while iterating through the elements. – Yoshi Mar 29 '12 at 14:04
  • Adding Yoshi's comment, map is returning new array, each is returning same array. So in this case needed to make new array, so it says you about using map. Less code is one another benefit. See this for more details http://stackoverflow.com/questions/749084/jquery-map-vs-each – Chuck Norris Mar 29 '12 at 14:05
  • 1
    @Chuck - Why would you use `map` and then run each loop on the array to get the sum if it can be achieved with just one loop? – ShankarSangoli Mar 29 '12 at 14:10
  • No need. I just show the way to count the sum. He can do at without map. – Chuck Norris Mar 30 '12 at 07:15
3
var total = 0;

$('#main input[id^="people_"]').each(function(){
     total += parseInt(this.value, 10);
});

Note that I am using attribute starts with selector to find all the input elements whose id starts with people_.

total will give you the total of all the input elements value.

ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
0

I guess you want this:

var hidden_value = new Array();
var hiddens = document.getElementById( "main" ).childNodes;
for( i = 0 ; i < hiddens.length ; i++ ){
    hidden_value.push( hiddens[ i ].value );
}
Michael Sazonov
  • 1,531
  • 11
  • 21
0

You could try something like this:

var peopleData = $("#main input[type=hidden]").serializeArray();
Kevin B
  • 94,570
  • 16
  • 163
  • 180
0

Putting values in a variable does not make sense. You can insert the values in a Array and perform your required operation

Ravi Jain
  • 1,452
  • 2
  • 17
  • 41
0

Using Plain Javascript

var els=document.getElementById('main').childNodes;
var a​llVal​=​​​​​​​​[];
for(i=0; i<els.length-1; i++)
{
    if(els[i].nodeType != 3 && els[i].type=="hidden") allVal.push(els[i].value); 
}
console.log(allVal); // the array
console.log(allVal[0]); // first value

An example is here.

The Alpha
  • 143,660
  • 29
  • 287
  • 307