views:

559

answers:

4

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.

+1  A: 

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 newAray = new Array();

$("input:text[name=task]").each(function(){
    newArray.push($(this));
});
rahul
@rahul: that won't do because he is dealing with multiple text boxes not one. If you know PHP, notice the name of the text box `task[]` which means there are supposed to be more than one text boxes.
Sarfraz
@rahul: your update won't help still in terms of making php array which can be done if the `[]` is suffixed with the name of the field.
Sarfraz
+5  A: 

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());
});
Sarfraz
why down vote???????????????
Sarfraz
+1 to counter..
Anurag
@Anurag: Thanks :)
Sarfraz
+4  A: 

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

Kobi
@Kobi this is working good with the 1,2,3 so i'll use this with the explode function of php to get it sortedthanks @all for helping
x4tje
@x4tje - no problem. You don't have to use explode - note that `values` is an array, not a string. It depends on how you do your AJAX call, or course.
Kobi
+2  A: 

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());
});
Mailslut