Article Description:
This article describes a way to generate HTML from a JSON string (simply implement a text box, password box, Drop-down box). Just feel fun to do this, if you feel that there is no value, please ignore. Not enough to point out the hope that you Daniel. Follow-up will be based on your guidance to continue to improve.
function Description:
Enter the JSON string in the left input box and display the corresponding HTML (using Jquery1.4.4) according to the input JSON string in the right display area when you click Execute.
Html:
Copy Code code as follows:
<table style= "width:100%; ">
<col width= "200px;"/>
<tr>
<td>json Input Box </td>
<td> Show Area </td>
</tr>
<tr>
<td>
<textarea id= "Txtjson" rows= "cols=" >
</textarea>
</td>
<TD valign= "Top" >
<div id= "Divshow" >
</div>
</td>
</tr>
<tr>
<td></td>
<td>
<input id= "btnexec" type= "button" value= "Execute"/>
</td>
</tr>
</table>
JS Code:
Copy Code code as follows:
$ (document). Ready (function () {
$ ("#btnExec"). Click (function () {
try{
var objlist = eval ($ ("#txtJson"). Val ());
Jsontocontrol (objlist);
}
catch (e) {
Alert ("JSON format error");
}
});
});
function Jsontocontrol (jsonobj) {
$ ("#divShow"). empty ();
$.each (jsonobj, function (index, item) {
var control = null;
var title = $ ("<label/>");
Switch (item.type) {
Case "TextBox":
Control = CreateTextbox ();
Break
Case "SELECT":
Control = Createselect (item);
Break
Case "Password":
Control = Createpassword ();
Break
//------------------------------
The other controls add code here
//------------------------------
}
if (item.title!= null) {
Title.text (Item.title);
}
if (control!= null) {
Control = Setattritube (control, item);
$ ("#divShow"). Append (title);
$ ("#divShow"). Append (Control);
$ ("#divShow"). Append ("<br/>");
}
})
}
To set the style of a control
function Setattritube (control, item) {
if (item.width!= null) {
Control.width (Item.width);
}
//--------------------------------
Other styles Add code here
//--------------------------------
return control;
}
Create TextBox
function CreateTextbox () {
Return $ ("<input type= ' textbox '/>");
}
Create a password box
function Createpassword () {
Return $ ("<input type= ' password '/>");
}
Create a Select
function Createselect (item) {
var C = $ ("<select></select>");
if (item.items!= null) {
$.each (Item.items,function (index,i) {
$ ("<option value= '" +i.key+ "' checked= ' checked ' >" +i.value+ "</option>"). Appendto (c);
})
}
return C;
}
Thank you very much for taking the time to finish. If you have any comments or suggestions, please leave a message.