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!
Use: http://jsfiddle.net/xH79d/
var n = $("input[name^='card']").length;
var array = $("input[name^='card']");
for(i=0; i < n; i++) {
// use .eq() within a jQuery object to navigate it by Index
card_value = array.eq(i).attr('name'); // I'm assuming you wanted -name-
// otherwise it'd be .eq(i).val(); (if you wanted the text value)
alert(card_value);
}
?
You can just loop though the items:
$("input[name^='card']").each(function() {
console.log($(this).val());
});
to read an array
, you can also utilize "each
" method of jQuery
:
$.each($("input[name^='card']"), function(index, val){
console.log(index + " : " + val);
});
bonus: you can also read objects through this method.
jQuery
collections have a built in iterator with .each
:
$("input[name^='card']").each(function () {
console.log($(this).val());
}
Your syntax is incorrect.
card_value = $(array[i]).val();
or card_value = array[i].value;
array[i] is not a jQuery object (for some reason).
Checking your browser's console can be helpful for things like this.
Use map function
var values = $("input[name^='card']").map(function (idx, ele) {
return $(ele).val();
}).get();
Source: Stackoverflow.com