abilash er abilash er - 14 days ago 5
jQuery Question

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

Answer

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>

Comments