Gregg
Gregg

Reputation: 35904

Mapping JSON properties to HTML ID to Easily Set Values

Assuming I have something like the following:

var address = {id: 100, name: "Gregg", addressOne: "111 1st Street"};

And an HTML form:

<input id="name" />
<input id="addressOne" />

I want to know if there is a way to iterate over all the INPUT elements of the form, and set their values based on the JSON object's properties. The following is the long approach I could take:

$.each($("input"), function(idx, input) {
   if (input.attr("id") == "name") input.val( address.name );
   if (input.attr("id") == "addressOne") input.val( address.addressOne );
});

I want to know if there is a way to do the above without the IF statements. Is there some way in JavaScript to dynamically map the two together. I hope this makes sense.

Upvotes: 2

Views: 593

Answers (6)

sgroh
sgroh

Reputation: 354

I think that this would work, but I redefine the var address to a JSON object.

var address = {id: 100, name: "Gregg", addressOne: "111 1st Street"}

And the iterator could be:

$.each($("input"), function(idx, input) {
    $(this).val( address[input.id] );
});​

I hope this helps.

Upvotes: 0

Kevin Boucher
Kevin Boucher

Reputation: 16705

<input type="text" id="name" />
<input type="text" id="addressOne" />

var address = { id: 100, name: "Gregg", addressOne: "111 1st Street" },
prop, $field;

for ( prop in address ) {
    $( "#" + prop ).val( address[prop] );
}

Note the address variable is now an object literal rather than an array.

Fiddle: http://jsfiddle.net/kboucher/Gt9ND/

Upvotes: 0

The Alpha
The Alpha

Reputation: 146269

You may try this

$('input').each(function(){
    $(this).val(address[this.id]);
});

DEMO.

Upvotes: 0

Ram
Ram

Reputation: 144739

You can use val method:

$('input').val(function(i, v){
    return address[this.id]
})

http://jsfiddle.net/GKUMk/

Upvotes: 5

Lyn Headley
Lyn Headley

Reputation: 11608

$("#name").val(address.name);
$("#addressOne").val(address.addressOne);

Upvotes: 1

saml
saml

Reputation: 6802

$.each($("input"), function(idx, input) {
   if (address[input.attr("id")]) {
       address[input.attr("id")]
   }
});

Upvotes: 0

Related Questions