Looks like my main issue was using .val() when I should have been using map, thank you @Barmar!
Though I’m still looking for a way to achieve the second array structure at the bottom of my post. It seems like the HTML structure would have to be:
<div>
<input type="text" name="student[1][name]">
<input type="number" name="student[1][score]">
<input type="text" name="student[2][name]">
<input type="number" name="student[2][score]">
<input type="text" name="student[3][name]">
<input type="number" name="student[3][score]">
</div>
The challenge with this is the ID number is dynamic, so I’m not sure how to fit this in a Jquery selector. Would I just be selecting by "student" i.e.
let input_names = $('input[name^="student["]').map(function() {
return this.value;
}).get();
I have a lot of inputs that are of the same kind so I want them in arrays, i.e.
<div>
<input type="text" name="name_[1]">
<input type="number" name="score_[1]">
<input type="text" name="name_[2]">
<input type="number" name="score_[2]">
<input type="text" name="name_[3]">
<input type="number" name="score_[3]">
</div>
The number in-between the brackets is the ID grouping related elements together. I want to be able to send all the values in arrays in an AJAX request but can’t seem to figure it out. Only the first elements get sent, not an array
let input_names = $('input[name^="name_"]').val();
let input_scores = $('input[name^="score_"]').val();
$.ajax({
url: "../util/funcs.php",
async: true,
data: {
a: "backendFunction",
input_names: input_names,
input_scores: input_scores
}
})
.done(function(data) {
console.log("Success");
})
.fail(function() {
console.log("Error");
.always(function() {
// alert( "complete" );
});
I want a way to neatly send them to the backend, either as separate arrays by name parameter or ideally grouped by ID. So the $_REQUEST would look something like:
[ids] =>
[1, 2]
[names] =>
["alex", "john"]
[scores] =>
[30, 70]
Or even better:
[1] =>
[name] => "alex"
[score] => "30"
[2] =>
[name] => "john"
[score] => "70"
Unfortunately either way I try, the AJAX only seems to send the first of each input, rather than arrays. Please help!
3
Answers
.val()
only returns the value of the first element that matches the selector, not all of them. You need to loop over all the matches to get all the values.Here is a solution to get your desired object format:
Output:
Notes:
{ name, value }
objects.reduce()
to accumulate the desired object format.replace()
ofnum
andkey
if you have different name input patterns