Reputation: 1548
In one of my HTML page, there are a few input fields with the same name attributes since I want to send them as an array to another PHP for back-end transactions.
Suppose the input field like below :
<input type="text" name="language_names[]" value="english">
<input type="text" name="language_names[]" value="french">
<input type="text" name="language_names[]" value="spanish">
Now I want to use Jquery to send this array? I am using the .post() method for this, I know for single value it could be send as {key1: value1, key2:value2...}, but for array How can I do it like this ? I guess it should be close to
{'language_names[]' : $('#input[name="language_names[]"]').val()}
But it doesn't work (I check the request body). Anyone can help ?
Upvotes: 2
Views: 887
Reputation: 471
Since you need a simple array with the values of those specific input elements, you could use something like:
function getLanguageValues() {
var language_names = [];
$.each($("input[name=language_names\\[\\]]"), function (indexInArray, valueOfElement) {
language_names.push($(valueOfElement).val());
});
return language_names;
}
Here is the jsfiddle.
Upvotes: 0
Reputation: 1340
Or you can also do this :
{'language_names[]' : $('input[name=language_names\\[\\]]').serialize()}
Upvotes: 0
Reputation: 11830
Use serialize function of jquery like this
// This returns a json representation of your form values
$('#formid').serialize();
Upvotes: 5