1

I have a json object;

a.Name = "John";
a.Nick = "Smith";
a.Info = "hi there";

and some html like this:

<input id="Name" />
<input id="Nick" />
<input id="Info" />

is it possible to automatically set the values of these inputs according the object's property names ?

What I'd like to do is to loop through the object's properties and look for an input with same id and set it's value.

3 Answers 3

7

Since IDs should be unique anyway, here’s a more efficient solution:

$.each(a, function(k, v) {
  $('#' + k).val(v);
});

Of course, this is even faster:

$.each(a, function(k, v) {
  (document.getElementById(k) || {}).value = v;
});

If you prefer not to use jQuery at all, you could do it like this:

for (var i in a) {
  (document.getElementById(i) || {}).value = a[i];
});

Edit: Updated the last two answers, since OP mentioned that some inputs might not exist.

Sign up to request clarification or add additional context in comments.

2 Comments

getElementById() is internally used by jQuery when using a # selector so it won't be much faster ;-)
Btw, +1 for the # selector, IDs "should" (depends of the developer ;-)) be unique. I just didn't want to apply some val() to anything else than an input, in case you have a duplicated ID with the same key.
7

You want to do this?

$.each(a, function(k,v) {
    $('input[id='+k+']').val(v);
})

2 Comments

some inputs might not exist, is this ok?
Yes, the val() method will be applied on a empty jQuery object, which is OK, it won't throw any error.
1

try this:

for (var prop in a) { 
  alert(propertyName + ' => ' + a[propertyName]); 
}

this version don't need jQuery ;)

Comments

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.