Ad

Get Input Value By Looping Name Selector

- 1 answer

I want to loop through a list of element which have dynamic name's value, like item1,item2 etc. but I got undefined like below.

len = $('.aws').length + 1;

var obj = [],
  temp = {};

for (var i = 1; i <= len; i++) {
  console.log(i)
  temp["index"] = $('.aws[name="item' + i + '"]').val()
  obj.push(temp);
}

console.log(obj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" class="aws" name="item1" value="1.jpg">
<input type="hidden" class="aws" name="item2" value="2.jpg">

Ad

Answer

The problem is that you're pushing a reference to the same object on each iteration. In doing so, the index property on the temp object will be the value from the last iteration.

In addition, there are only two elements, and the for loop was executed three times because of the condition i <= len (it should have been i < len). Due to this, the value was undefined on the last iteration, because the element doesn't exist. This resulted in all the index properties on the temp property being set to undefined.

If you want a native JS solution, you could simply use the following instead:

var elements = document.querySelectorAll('.aws');
var values = [];

for (var i = 0; i < elements.length; i++) {
  values.push({index: elements[i].value});
}

In the snippet above, a new object is pushed to the values array on each iteration (rather than a reference to the same object). The for loop condition is also i < elements.length (rather than i <= elements.length), so it will only iterate 2 times (rather than 3 like in your example).


If you want a shorter jQuery solution, simply use the .map() method:

var values = $('.aws').map(function () {
  return {index: this.value };
}).get();
Ad
source: stackoverflow.com
Ad