I have HTML form with many inputs, after submitting the form I should get these values as JSON format, the challenge here is that the form has dynamic fields that can be increased/decreased during form filling. I’m trying to handle these inputs but I couldn’t reach the desired result which is to put each of group of the dynamic fields inside an array.
I am posting this JSON using AJAX but if there is PHP approach to achieve this it’s ok.
This is the output that I get:
output example
This is the desired result:
desired example
This is the JS code that I use:
function convertFormToJSON() {
var data = $('#editForm');
const array = $(data).serializeArray();
const json = {};
const tempItems = {};
$.each(array, function () {
if (this.name.includes('items')){
tempItems[this.name] = this.value || "";
}else{
json[this.name] = this.value || "";
}
});
json['items'] = tempItems;
console.log(json);
}