Reputation: 137
I need to get all text of value, then use json to send the value to insert all of price to the database, but i had the problem, i can't get the text of all value where input text name='price'. here this is HTML code:
<input type='text' id='price1' name='price[]'/>
<input type='text' id='price2' name='price[]'/>
<button type='button' id='btn'/>
and this is JS code:
$('#btn').click(function (e) {
var myprice = [];
myprice = $("*[name='price']").val();
$.post(
"index.php",
{
type: "insert",
price: myprice,
}
).done(function (data) {
console.log(data);
})
});
Upvotes: 0
Views: 77
Reputation: 34426
You can loop through your items (no brackets needed, no change to your HTML) and add them to the array easily -
$('#btn').click(function (e) {
e.preventDefault();
var myprice = [];
$("*[name='price']").each(function() {
myprice.push( $(this).val() );
});
console.log(myprice); // e.g., ["56", "42"]
});
Here is an EXAMPLE
Upvotes: 1
Reputation: 24648
You can use .map()
to get all the values:
var myprice = $('[name="price[]"]').map(function(i,v) {
return v.value;
}).get().join(',');
//result: "value1,value2..."
Or $.map()
:
var myprice = $.map($('[name="price[]"]'), function(v,i) {
return v.value;
}).join(',');
Upvotes: 3
Reputation: 28588
You cannot get values once, you need to iterate as you need multiple input values.
and use the correct name, change your html:
<input type='text' id='price1' name='price'/>
<input type='text' id='price2' name='price'/>
and code:
var myprice = [];
for(var i=0; i < $("*[name='price']").length; i++){
myprice.push($("*[name='price']:eq("+i+")").val());
}
Upvotes: 2