Form Populate From JSON
by javajack
HTML
<form name="form_simple" action="details.html" method="get">
<input type="hidden" name="ID" />
<br/>
<label for="Name">Name</label>
<input name="Name" type="text" />
<br/>
<label for="Address">Address</label>
<textarea name="Address" rows="5" cols="20"></textarea>
<br/>
<label for="Country">Country</label>
<select name="Country" multiple="multiple">
<br/>
<option value="">-</option>
<option value="UK">United Kingdom</option>
<option value="SRB">Serbia</option>
<option value="USA">United States of America</option>
<option value="FRA">France</option>
</select>
<br/>
<label for="IsFeatured">Is Featured</label>
<input name="IsFeatured" type="checkbox" value="ADMIN"/>
<input name="IsFeatured" type="checkbox" value="AGENCY"/>
<input name="IsFeatured" type="checkbox" value="AGENT"/>
<br/>
<label for="Town">Town</label>
<select name="Town">
<option value="" selected="selected">-</option>
<option value="London">London City</option>
<option value="Liverpool">Liverpool City</option>
<option value="Lothian">Lothian City</option>
<option value="Newcastle">Newcastle City</option>
<option value="Buckinghamshire">Buckinghamshire City</option>
<option value="Essex">Essex City</option>
</select>
<br/>
<label for="Contact">Contact</label>
<input name="Contact" type="radio" value="Email" />Email
<input name="Contact" type="radio" value="Phone" />Phone
<input name="Contact" type="radio" value="Post" />Post
<br/>
<input type="submit" value="Save" class="submit-button" />
</form>
JavaScript
data = {
"ID": 17,
"Name": "Emkay Entertainments",
"Address": "Nobel House, Regent Centre",
"Town": "Lothian",
"Country":["UK","USA"],
"Contact": "Post",
"IsFeatured": ["ADMIN","AGENT"]
};
// reset form values from json object
$.each(data, function (name, val) {
var $el = $('[name="' + name + '"]'),
type = $el.attr('type');
switch (type) {
case 'radio':
$el.filter('[value="' + val + '"]').prop('checked', 'checked');
break;
default:
$el.val(val);
}
});
var amdin = "ADMIN" ;
var amdinSelector = "input[type=checkbox][name=IsFeatured][value="+amdin+"]";
console.log("Is Admin Checked : " + $(amdinSelector).is(':checked'));