My input field is as below:
<input type="hidden" name="data[{{ $parentIndex }}][{{ $index }}]" value="{{ $value }}">
My sample data:
<input type="hidden" name="data[0][0]" value="Name">
<input type="hidden" name="data[0][1]" value="contact_email">
<input type="hidden" name="data[0][2]" value="phone number">
<input type="hidden" name="data[0][3]" value="contact_location">
<input type="hidden" name="data[0][4]" value="">
<input type="hidden" name="data[1][0]" value="John Doe">
<input type="hidden" name="data[1][1]" value="[email protected]">
<input type="hidden" name="data[1][2]" value="15551-234567">
<input type="hidden" name="data[1][3]" value="New York, NY">
<input type="hidden" name="data[1][4]" value="230">
<input type="hidden" name="data[2][0]" value="Jane Smith">
<input type="hidden" name="data[2][1]" value="[email protected]">
<input type="hidden" name="data[2][2]" value="15552345678">
<input type="hidden" name="data[2][3]" value="Los Angeles, CA">
<input type="hidden" name="data[2][4]" value="5201">
<input type="hidden" name="data[3][0]" value="Robert Johnson">
<input type="hidden" name="data[3][1]" value="[email protected]">
<input type="hidden" name="data[3][2]" value="8.80156E+13">
<input type="hidden" name="data[3][3]" value="Chicago, IL">
<input type="hidden" name="data[3][4]" value="4110"
I was to access the data using below code:
var data =$('input[name="data[]"]').map(function () {
return $(this).val();
}).get();
But it results empty array while I console.log(data)
the data variable.
I have used following lines of code as well but it prints single array by combining the whole data.
var data =$("input[name^='data']").map(function () { return $(this).val(); }).get();
How do I get the array input here?
2
Answers
Here is one way of solving the issue. The form entries can be supplied by jQuery’s
.serializeArray()
method or by using the Vanilla-JS’sFormData
class:The function
processForm()
is just a simple implementation in which I assume that thename
attribute of an<input>
element can have either two indexes (i and j) or none. I then treat thevalue
of the input element accordingly by either creating a sub- and sub-array fornam
ino
and placingvalue
there or by storingvalue
in the string-typed propertynam
.You can use regex in css selector, based on example data :
And then use JQuery to map them :
The idea is to map the header at the first row, and the data for the next row.
The header row has
data[0]
pattern, and not for the data row, so we can use:not()
selector to exclude header row