Wasser Trinker Wasser Trinker - 2 months ago 17
HTML Question

Bind JSON object to HTML element

I want to bind a JSON object to a HTML element.


I have a object "person" with the attributes "firstName", "lastName"

<div class="person-list">
<div class="person-list-item">
<div>John</div> ---> bind it to person.firstName
<div>Smith</div> ---> bind it to person.lastName

so, if a value of the HTML elements gets changed, then will also the object person gets updated.

is this possible in any way?

i use:

  • jquery



If you'll be doing this a lot in your application, you may want to bring in a library such as the excellent Knockout.js which uses MVVM to do bindings as you describe.

Your markup would look something like this:

<div data-bind="text: firstName"></div>
<div data-bind="text: lastName"></div>

And in your JavaScript:

function MyViewModel() {
    this.firstName = "John";
    this.lastName = "Smith";

ko.applyBindings(new MyViewModel());

You can also use a data set if there are many "people." Try out this tutorial if you would like to learn how to do that: Working with Lists and Collections.

Other useful links: