How to get an Array with jQuery, multiple <input> with the same name
I have a form where users can add input fields with jQuery.
<input type="text" id="task" name="task[]" />
After submitting the form I get an array in PHP.
I want to handle this with the $.ajax()
but I have no idea how to turn my <input>
s to an array in jQuery.
Thanks in advance.
Using map:
var values = $("input[id='task']")
.map(function(){return $(this).val();}).get();
If you change or remove the id (which should be unique), you may also use the selector $("input[name='task\\[\\]']")
Working example: http://jsbin.com/ixeze3
For multiple elements, you should give it a class rather than id eg:
<input type="text" class="task" name="task[]" />
Now you can get those using jquery something like this:
$('.task').each(function(){
alert($(this).val());
});
Firstly, you shouldn't have multiple elements with the same ID on a page - ID should be unique.
You could just remove the id attribute and and replace it with:
<input type='text' name='task'>
and to get an array of the values of task do
var taskArray = new Array();
$("input[name=task]").each(function() {
taskArray.push($(this).val());
});
To catch the names array, i use that:
$("input[name*='task']")
You can't use same id for multiple elements in a document. Keep the ids different and name same for the elements.
<input type="text" id="task1" name="task" />
<input type="text" id="task2" name="task" />
<input type="text" id="task3" name="task" />
<input type="text" id="task4" name="task" />
<input type="text" id="task5" name="task" />
var newArray = new Array();
$("input:text[name=task]").each(function(){
newArray.push($(this));
});