What would be the best way to create a multidimensional associative array from form inputs?
The form looks like this:
<div id="items">
<h4>Engraving Text</h4>
<div class="item" data-position="1">
<h4 id="engraving-item">Item 1</h4>
<label>Engraving Line 1: </label>
<input type="text" class="engraving-input engraving-line1" name="trophy" id="item1-line1">
<br />
<label>Engraving Line 2: </label>
<input type="text" class="engraving-input engraving-line2" name="trophy" id="item1-line2">
<br />
<label>Engraving Line 3: </label>
<input type="text" class="engraving-input engraving-line3" name="trophy" id="item1-line3">
<br />
</div>
</div>
If the user enters that they want multiple items - additional inputs are dynamically added to the form using these first 3 as a template.
I'm looking to create this sort of array (for example if the user added 2 items):
var myArray = {
item1 :
[
{
engraving-line1 : "user entered data",
engraving-line2 : "more user data",
engraving-line3 : "yep, more data"
}
],
item2 :
[
{
engraving-line1 : "user entered data",
engraving-line2 : "more user data",
engraving-line3 : "yep, more data"
}
]
};
I had written this but I think I am headed in the wrong direction with it or at the very least - writing it poorly.
var totalItems = $("#quantity_wanted").val();
jsonObj = [];
i=1;
while (i < totalItems){
items = {};
$('.item[data-position="'+i+'"] :input').each(function(){
var name = $(this).attr("name");
var engraving = $(this).val();
item = {}
item ["name"] = name;
item ["engraving"] = engraving;
items.push(item);
});
jsonObj.push(items)
i++;
}
Just looking for help writing the javascript that will help me to iterate through the inputs on the screen and push them into a multidimentional associative array like the one I listed.
idof anhtmlelement should be uniqueitems = {};should beitems = [];. Theobjectprototype doesn't have apushmethod. And make sure you declare your variables properly:var items = [];