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!
prototype. values() The values() method returns a new array iterator object that iterates the value of each index in the array.
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.
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.
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.
Use map function
var values = $("input[name^='card']").map(function (idx, ele) {
return $(ele).val();
}).get();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With