I have multiple forms on a page where each form will add individual item to the database. There’s also an ‘Add all’ button that’ll send all products data.
See basic html below:
<button type="submit">All all products</a>
<form>
<input type="hidden" name="Product" value="ProductA" />
<input type="checkbox" name="optionAll" value="Option All" /> Option All
<input type="checkbox" name="option" value="Option 1" checked="checked" /> Option 1
<input type="checkbox" name="option" value="Option 2" /> Option 2
<button type="submit">Add this product"</button>
</form>
<form>
<input type="hidden" name="Product" value="ProductB" />
<input type="checkbox" name="optionAll" value="Option All" /> Option All
<input type="checkbox" name="option" value="Option 1" checked="checked" /> Option 1
<input type="checkbox" name="option" value="Option 2" checked="checked" /> Option 2
<button type="submit">Add this product"</button>
</form>
I’m trying to post the serialized form data into the following JSON format:
products = {
"ProductA": {
"option": ["Option 1"] // only 1 checkbox is checked
},
"ProductB": {
"optionAll": "Option All",
"option": ["Option 1", "Option 2"] // both checkboxes are checked
}
}
I’ve been playing around with mapping the serialized data but couldn’t get it into the JSON format like above.
data = $.map($('form').serializeArray(), function(el, i){
var json = {};
???
return json;
});
console.log(data)
Appreciate your help!
1 Answer