After spending all night trying various solutions, I still can't find the right answer for my Javascript needs as a beginner.
The solution I attempted to convert my form data into an object is:
$('input.submit').click(function(e){
e.preventDefault();
var formData = $('form.anything').serializeArray();
console.log(formData);
});
The array output looks like the image link below:
View output of using serializeArray()
I tried using jQuery to convert it into an array of objects, but the methods I found didn't give me the desired format.
$.fn.serializeObject = function() {
var storedData = {};
var formData = this.serializeArray();
$.each(formData, function() {
if (storedData[this.name]) {
if (!storedData[this.name].push) {
storedData[this.name] = [storedData[this.name]];
}
storedData[this.name].push(this.value || '');
} else {
storedData[this.name] = this.value || '';
}
});
The output I received was this:
View output using the serializeObject()
Although the output from these attempts is closer to the object format I am looking for, there are still challenges. Hope this information helps!
Expected Output:
[
cashin: [
0: {
name: [...],
amount: [...],
type: [...]
},
1: {
name: [...],
amount: [...],
type: [...]
}
],
cashout: [
0: {
name: [...],
amount: [...],
type: [...]
},
1: {
name: [...],
amount: [...],
type: [...]
}
]
]
Update Information:
Here is the HTML code for the form:
<form id="cashin_form" class="anything" action="/cashins" accept-charset="UTF-8" method="post"><input type="hidden" name="authenticity_token" value="xxxx">
<!-- Form fields here -->
</form>
The input block will dynamically increase when the user clicks on the "Add Item" button. The challenge now is creating an object for each input due to the use of cashin[...]
and cashout[...]
in the form.