How to get an Array with jQuery, multiple <input> with the same name
Asked Answered
S

9

65

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.

Standfast answered 13/4, 2010 at 7:48 Comment(0)
U
124

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

Underage answered 13/4, 2010 at 7:52 Comment(11)
this is working good with the 1,2,3 so i'll use this with the explode function of php to get it sorted thanks @all for helpingStandfast
@Standfast - 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.Underage
why do we need .get() for?Corves
The .get() flattens the array of values into a string. If you did want the actual Javascript array of values, you should remove the ".get()".Wikiup
@Wikiup - $(...) returns an array-like jQuery wrapper. $(...).get() returns a real array of real DOM nodes, not a string.Underage
how can I do if I want to add for each element of the array, each index [n], another value? Example: <input type="text" class="name" /> <input type="text" class="surname" />Ureter
@Gabz - I'd target their container, something like $('.row').map(function(){var row = $(this); return {name: row.find('.name').val(), surname: row.find('.surname').val()};}).get();, which results in an array of objects, not just values. Feel free to ask a new question with your code if you need additional help. Thanks!Underage
I can't make it work :( thanks anyway, I'll post a new questionUreter
it works thanks! I forgot to change the function to alert the content of the array on the screen and it was blocking all the code when submitting!Ureter
Be careful with .map(), in some browsers it returns an array but in others it returns an object m.fn.init[] (Chrome). This latter one cannot be stringified by JSON.stringify(). Specifically, the following two are NOT equivalent: var arr=$('input[name="foo"]').map(function(){return this.value}).get() with var arr=[]; $('input[name="foo"]').each(function(){arr.push(this.value)}). In the first case arr is not an Array whereas in the latter case it is. JSON.stringify(arr) fails for the former, but works for the latter.Grasso
you are genius .. I have do this for select box.Oneness
V
35

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());
});
Vetiver answered 13/4, 2010 at 7:51 Comment(1)
@Vetiver please check it codepen.io/sidaurukfreddy/pen/XNroJW how can i prevent if kode barang has same value ? thanksSuborbital
C
17

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());
});
Cloutman answered 13/4, 2010 at 7:53 Comment(0)
K
10

To catch the names array, i use that:

$("input[name*='task']")
Kincaid answered 10/4, 2013 at 10:45 Comment(1)
This is actually the best answer here.Malia
G
9

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));
});
Gory answered 13/4, 2010 at 7:50 Comment(2)
@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.Vetiver
@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.Vetiver
A
1

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());
});
Archaeology answered 20/2, 2017 at 21:50 Comment(0)
C
0

if you want selector get the same id, use:

$("[id=task]:eq(0)").val();
$("[id=task]:eq(1)").val();
etc...
Criticize answered 3/9, 2014 at 2:21 Comment(0)
Z
0

You can use jquery.serializeJSON to do this.

Zigrang answered 16/10, 2016 at 21:33 Comment(0)
C
0

Q:How to access name array text field

<input type="text" id="task" name="task[]" />

Answer - Using Input name array :

$('input[name="task\\[\\]"]').eq(0).val()
$('input[name="task\\[\\]"]').eq(index).val()
Chemistry answered 14/9, 2019 at 4:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.