Description:
This article describes how to generate Html based on Json strings (simply implement the text box, password box, and drop-down box ). This is done only when you think it is fun. If you feel that there is no value, ignore it. I hope you can give me some advice. We will continue to improve it in the future based on your guidance.
Function Description:
Enter a Json string in the input box on the left. When you click execute, the corresponding Html is displayed in the display area on the right (Jquery1.4.4 is used) based on the input Json string)
HTML:
Copy codeThe Code is as follows:
<Table style = "width: 100%;">
<Col width = "200px;"/>
<Tr>
<Td> Json input box </td>
<Td> display area </td>
</Tr>
<Tr>
<Td>
<Textarea id = "txtJson" rows = "20" cols = "50">
</Textarea>
</Td>
<Td valign = "top">
<Div id = "divShow">
</Div>
</Td>
</Tr>
<Tr>
<Td> </td>
<Td>
<Input id = "btnExec" type = "button" value = "executed"/>
</Td>
</Tr>
</Table>
JS Code:
Copy codeThe Code is 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;
//------------------------------
// Add code to other controls
//------------------------------
}
If (item. title! = Null ){
Title. text (item. title );
}
If (control! = Null ){
Control = setattrube (control, item );
$ ("# DivShow"). append (title );
$ ("# DivShow"). append (control );
$ ("# DivShow"). append ("<br/> ");
}
})
}
// Set the widget Style
Function setattrube (control, item ){
If (item. width! = Null ){
Control. width (item. width );
}
//--------------------------------
// Add code here for other styles
//--------------------------------
Return control;
}
// Create a TextBox
Function createTextBox (){
Return $ ("<input type = 'textbox '/> ");
}
// Password creation box
Function createPassword (){
Return $ ("<input type = 'Password'/> ");
}
// Create 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 for taking the time to complete this article. If you have any comments or suggestions, leave a message.