Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 503
x4tje Avatar asked Apr 13 '10 07:04

x4tje


People also ask

How do you get multiple input values?

In C++/C user can take multiple inputs in one line using scanf but in Python user can take multiple values or inputs in one line by two methods. Using split() method : This function helps in getting multiple inputs from users. It breaks the given input by the specified separator.


6 Answers

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

like image 93
Kobi Avatar answered Sep 30 '22 14:09

Kobi


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());
});
like image 23
Sarfraz Avatar answered Sep 30 '22 14:09

Sarfraz


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());
});
like image 31
Dal Hundal Avatar answered Sep 30 '22 12:09

Dal Hundal


To catch the names array, i use that:

$("input[name*='task']")
like image 40
fxs Avatar answered Sep 30 '22 14:09

fxs


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));
});
like image 23
rahul Avatar answered Sep 30 '22 12:09

rahul


HTML:

<input type="text" name="task[]" class="form-control" id="task">

JS:

var tasks= new Array();
$('input[name^="task"]').each(function() 
{
tasks.push($(this).val());
});
like image 26
Antonio Reyes Avatar answered Sep 30 '22 13:09

Antonio Reyes