newbie
newbie

Reputation: 227

Generate HTML tags using JSON and jQuery

I have the following JSON schema

{
"employee":
             {"display_name":"EMPLOYEE NAME:",
              "format":"string",
              "type":"textbox",
              "dflt":"null",
              "isMandatory":"true"}
}

Now I have to generate an html tag i.e

<input type="text" value="name"></input>

How do I use the JSON with jQuery? I know I have to use append method. But I'm not sure how to append JSON elements.

Thanks

Upvotes: 4

Views: 13785

Answers (2)

hayesgm
hayesgm

Reputation: 9096

You can use $.parseJSON to parse your text into a JSON object. Then use jQuery to create any elements you want and append it where you want. (Here's a JSFiddle)

 var myJSON = '{ "employee": { "display_name":"EMPLOYEE NAME:", "format":"string", "type":"textbox", "dflt":"null", "isMandatory":"true" } }';

 var employee = $.parseJSON(myJSON).employee; //get employee object
 if (employee.type == "textbox") {
   $('<label>').attr({for: 'employee_name'}).text(employee.display_name).appendTo($('body'));
   $('<input>').attr({type: 'text', id:'employee_name'}).appendTo($('body'));
 }

This generates the HTML:

 <label for="employee_name">EMPLOYEE NAME:</label>
 <input type="text" id="employee_name">

I'm sure this is not exactly what you want, but this should definitely lead you in the right direction to solving your problem. Enjoy!

Upvotes: 12

doctororange
doctororange

Reputation: 11810

This might be what you're looking for: http://neyeon.com/p/jquery.dform/doc/files2/readme-txt.html

Upvotes: 1

Related Questions