Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve value from elements in array using jQuery?

I have multiple input fields like so:

<input type="text" name="card[]">
<input type="text" name="card[]">
<input type="text" name="card[]">

Users can add or remove these fields as required, therefore the name of the fields is an array. To get length of the array, this works fine:

var n = $("input[name^= 'card']").length;

How can I read value from the array?

I've tried this which didn't work:

var n = $("input[name^='card']").length;
var array = $("input[name^='card']");
for(i=0;i<n;i++)
{
 card_value=  array[i].val();
 alert(card_value);
}

This didn't work either:

var n = $("input[name^='card']").length;

for(i=0;i<n;i++)
{
 card_value=  $("input[name^='card["+i+"]']").val();
 alert(card_value);
}

How can I read value from this array? Help!

like image 932
Sushan Ghimire Avatar asked Aug 30 '12 22:08

Sushan Ghimire


People also ask

How do you find the value of an element in an array?

prototype. values() The values() method returns a new array iterator object that iterates the value of each index in the array.

How do you check value is exists in array in jQuery?

1) Using jQuery If you are someone strongly committed to using the jQuery library, you can use the . inArray( ) method. If the function finds the value, it returns the index position of the value and -1 if it doesn't.

How do you iterate through an array in jQuery?

The $.each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

What is $() in jQuery?

In the first formulation listed above, jQuery() — which can also be written as $() — searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements: 1. $( "div.


2 Answers

Use map function

var values = $("input[name^='card']").map(function (idx, ele) {
   return $(ele).val();
}).get();
like image 87
NewBee Avatar answered Nov 02 '22 21:11

NewBee


You should use:

card_value=  array.eq(i).val(); //gets jquery object at index i

or

card_value=  array[i].value; //gets dom element at index i
like image 23
scrappedcola Avatar answered Nov 02 '22 22:11

scrappedcola