0

I want to create a html page dynamically according to a JSON object and I implemented a method and its working fine my current code is given below

$(function(){
    var result =JSON.parse(response);
    var markup="";
    for (var i=0;i<result.length;i++) {
        markup+="<div id='nameDiv'>"+result[i].name+"</div>"; 
    }
    $('.divLoadData:last').after(markup);
});

But my actual markup is like this

 <div class="divLoadData">
     <div class="name" id="nameDiv">
         Name
     </div>
     <div class="numberb">
         <div id="age">
             Age
         </div>
     </div>
     <div class="numberb dob">
         <div id="dob">
             DOB
         </div>
     </div>
 </div>

and it will grow eventually so my current method is not capable for creating this kind markup so is there any other way to do the same.

4
  • I would strongly encourage you to not go down the path of creating dynamic html in pure javascript or Jquery. This is a much better use case for template based data binding. Look into something like KnockoutJS or other template based frameworks Commented Oct 1, 2013 at 4:39
  • Could you please explain what does grow eventually signifies? Commented Oct 1, 2013 at 4:41
  • Please also be aware than dom ids are supposed to be unique. Commented Oct 1, 2013 at 4:44
  • @KishorSubedi means more fields will be add to the current markup like ssn,address etc.. Commented Oct 1, 2013 at 4:46

1 Answer 1

3

I think jQuery Tmpl (jQuery Template) is what you need.

https://github.com/BorisMoore/jquery-tmpl

You can just setup the template then bind it with JSON data. It will build the html for you.

for simple example

$.tmpl( "<li>${Name}</li>", { "Name" : "John Doe" }).appendTo( "#target" );

suit your case example

var movies = [
      { Name: "The Red Violin", ReleaseYear: "1998" },
      { Name: "Eyes Wide Shut", ReleaseYear: "1999" },
      { Name: "The Inheritance", ReleaseYear: "1976" }
    ];

  var markup = "<li><b>${Name}</b> (${ReleaseYear})</li>";

  // Compile the markup as a named template
  $.template( "movieTemplate", markup );

  // Render the template with the movies data and insert
  // the rendered HTML under the "movieList" element
  $.tmpl( "movieTemplate", movies )
      .appendTo( "#movieList" );

Hope this help.

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

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.