Home > Software design >  set value array in all inputs with same tag class
set value array in all inputs with same tag class

Time:03-30

I'm trying to do loop over all tag with same className and get their value:

var quantity = [];
$(".add_more_items").each(function(){
    quantity.push($(this).val());
});

this is a result, for example:

['1', '9', '1']

but my problem is I'm trying to set value from this array to other input with same class:

$.each(quantity, function(index, val){
    $(".items_final").val(val);
});

but always set in all inputs last value from my array, i don´t know what I'm doing wrong.

CodePudding user response:

Use an index assuming there is 1 to 1 mapping between the fields

const $final = $(".items_final");
$(".add_more_items").each(function(i, item) {
  $final[i].value = item.value; // or $final.eq(i).val(item.value)
});

const $final = $(".items_final");
$(".add_more_items").each(function(i, item) {
  $final[i].value = item.value; // or $final.eq(i).val(item.value)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Add more</h3>
<input type="text" value="1"  />
<input type="text" value="2"  />
<input type="text" value="3"  />
<input type="text" value="4"  />
<hr/>
<h3>final</h3>
<input type="text" value=""  />
<input type="text" value=""  />
<input type="text" value=""  />
<input type="text" value=""  />

Also this is useful:

const quantity = $(".add_more_items").map(function(){
  return this.value; // or $(this).val()
}).get();
  • Related