1

I have a form that I need to populate with JSON data. The form contains select, textarea, and input elements that need to be populated. The JSON data is complex / hierarchical (i.e. many nested objects).

I am aware of http://www.keyframesandcode.com/code/development/javascript/jquery-populate-plugin/ but it uses square bracket notation to map to field names (e.g.

<input name="person[name][last]" ...

I need to use dot notation though (e.g.

<input name="person.name.last" ...

I'm using jQuery so a jQuery solution is fine. Thanks.

1 Answer 1

1

Here's a hacked together alternative to populate using a recursive function:

function populator(json, nodes){
  $.each(json, function(key, value){
    newNodes = nodes ? nodes.slice() : [];
    newNodes.push(key);

    if (typeof(value)=="object") {
        populator(value, newNodes);
    else
        $('name["' + newNodes.join('.') + '"]').val(value);
    }
  });
}

With this you can do:

populator({
             person: {
                name: {
                   last: 'Doe', 
                   first: 'John'
                },
                address: {
                   street: '123 Main Street',
                   city: 'Montgomery',
                   state: 'AL'
             }
          });
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer. BTW, what's the purpose of nodes.slice(). Doesn't slice with no arguments simply return the original array?
No, it returns a clone of the array. The array needs to be cloned, because it can't be modified across iterations of nodes.
One thing, this won't work for multiple choice items (checkbox lists, multiple selects) as is. It will need some tweaking to get that to work, basically a smart array handler.

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.