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.
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.
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));
});
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());
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With