user7161552
user7161552

Reputation:

javascript array not working

this is my html strcture

<div class="parent">
    <input class="child1" value="1">
    <input class="child2" value="2">
    <input class="child3" value="3">

</div>

i need to make a javascript array

combined_array={child1:"1", child2:"2", child3:"3"};

for this i write the following code . But it is not correct . Please help to find out error

$('.parent').children('input').each(function () {
                              var c_class=$(this).attr("class");
                              var c_value=$(this).val();
                              var combined_array={c_class:c_value};
                          });

                       alert(combined_array);

Upvotes: 0

Views: 2363

Answers (2)

sujit kinage
sujit kinage

Reputation: 27

var combined_array={};
$('.parent').children('input').each(function () {
       combined_array[$(this).attr("class")]=$(this).val();
});
console.log(combined_array);
//alert(combined_array);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="parent">
    <input class="child1" value="1">
    <input class="child2" value="2">
    <input class="child3" value="3">
</div>

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115272

You are re-initializing the combined_array variable on each iteration so the result would be an object containing single property.

Instead initialize object outside and define property within the each() method callback.

var combined = {};
$('.parent').children('input').each(function() {
  var c_class = $(this).attr("class");
  var c_value = $(this).val();
  combined[c_class] = c_value;
});

console.log(combined);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <input class="child1" value="1">
  <input class="child2" value="2">
  <input class="child3" value="3">

</div>

Upvotes: 3

Related Questions