manishjangir
manishjangir

Reputation: 1695

Get all div values of similiar id in a particular div

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

Upvotes: 1

Views: 1068

Answers (6)

The Alpha
The Alpha

Reputation: 146191

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.

Upvotes: 0

ShankarSangoli
ShankarSangoli

Reputation: 69905

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.

Upvotes: 3

Chuck Norris
Chuck Norris

Reputation: 15190

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

Upvotes: 5

Ravi Jain
Ravi Jain

Reputation: 1482

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

Upvotes: 0

Kevin B
Kevin B

Reputation: 95020

You could try something like this:

var peopleData = $("#main input[type=hidden]").serializeArray();

Upvotes: 0

Michael Sazonov
Michael Sazonov

Reputation: 1533

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

Upvotes: 0

Related Questions