I want to bind a JSON object to a HTML element.
e.g.
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
</div>
</div>
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:
data-bind="foreach: list" It is similar of using for-each loop in javascript. It will iterate over all the elements in list from DataModel (Json object). <img data-bind = "attr: {src: url}"/> Here we are binding src attribute of <img>tag with a property (named 'url' ) of a list node in DataModel (Json object).
The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.
As long as your data is formatted as one of these types, it should be valid. However, if your data contains HTML, there are certain things that you need to do to keep the browser happy when using your JSON data within Javascript. Escape the forward slash in HTML end tags. <div>Hello World!
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:
Simple one-way approach using jquery...
var resp = your_json_data;
$(function () {
$(".jsondata").each(function () {
$(this).html(eval($(this).attr("data")));
});
});
then in the page...
<span class="jsondata" data="resp.result.formatted_phone_number" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With