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 ?
-
Have a look at jQuery serialize() api.jquery.com/serializeJay Blanchard– Jay Blanchard2013年04月23日 12:28:19 +00:00Commented Apr 23, 2013 at 12:28
3 Answers 3
Use serialize function of jquery like this
// This returns a json representation of your form values
$('#formid').serialize();
1 Comment
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.
Comments
Or you can also do this :
{'language_names[]' : $('input[name=language_names\\[\\]]').serialize()}