0

I have a JSON object returned from the database. The values in the JSON object came from an HTML page full of input tags.

var userTemplate = { };
$("#tabBasic").find($("input")).each(function() {
    userTemplate[this.name] = this.value;
});

Now I'd like to re-apply the values from the JSON to the input tags on the page.

Is there a way to do this automatically using jQuery?

1 Answer 1

2

You've just got the assignment reversed.

$("#tabBasic").find("input").each(function() {
    this.value = userTemplate[this.name];
});

I assume that each input has a unique name attribute.


You could also pass a function to the val()[docs] method. The return value is assigned as the new value.

$("#tabBasic").find("input").val(function() {
    return userTemplate[this.name];
});
Sign up to request clarification or add additional context in comments.

2 Comments

+1 I didn't know about the .val() function argument, cool! In this example, however, wouldn't it be better to cut to the chase and select for $('#tabBasic input') instead? Maybe even $('input', '#tabBasic')?
@richardneililagan: It depends. Doing an ID selection followed by a .find() will actually perform better in some browsers. And $('input', '#tabBasic'), while concise is ultimately turned into $("#tabBasic").find("input") under the hood, so it ends up being slower because of the conversion (and less readable IMO). In most cases, the performance difference between the 3 will be negligible, and it will come down to personal preference. :)

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.