3

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.

4
  • id of an html element should be unique Commented Feb 12, 2016 at 15:41
  • udpated. Thank you! Commented Feb 12, 2016 at 15:42
  • Which part isn't working? Commented Feb 12, 2016 at 15:44
  • 2
    items = {}; should be items = [];. The object prototype doesn't have a push method. And make sure you declare your variables properly: var items = []; Commented Feb 12, 2016 at 15:49

1 Answer 1

4

Your code could be much simplified.

  1. data-position attribute in jquery selector doesn't make sense since you don't actually use its value. You just need to select all input group containers by their shared class (.item), then, for each container, select all descendant inputs.
  2. Your code building item element is redundant. You can use inline object literal/initializer ({...}) instead.

Furthermore, as @Andy noted, items array should be initialized by array literal ([]), not object ({}).

So the code should look like this:

var jsonObj = [];
$('div.item').each(function(){
    var items = [];
    $(this).find('input').each(function() {
        items.push({
            name: $(this).attr("name"), engraving: $(this).val()
        });       
    });
    jsonObj.push(items) 
});
Sign up to request clarification or add additional context in comments.

1 Comment

A much more beautiful way to be sure. This works a treat. On my first input I have a button to 'repeat' the user input over all the following inputs on the page (so if they wanted to copy the same line 1 to each item they can) - is there a nice way to write it to avoid putting those inputs in the array (although I guess it doesn't really matter)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.