JSFiddle - React, Tailwind, and code Playground
HTML
<div id="myForm">
<div><span style="width:85px; float:left;">Name:</span><label class="dfName clearMe"></label></div>
<div style="clear:both;"><span style="width:85px; float:left;">Email:</span><input type="text" class="dfEmail"></input></div>
<div style="clear:both;"><span style="width:85px; float:left;">Checked:</span><input type="checkbox" class="dfCheck1"></input></div>
<div style="clear:both;"><span style="width:85px; float:left;">Unchecked:</span><input type="checkbox" class="dfCheck2"></input></div>
<div style="clear:both;"><span style="width:85px; float:left;">Car:</span><select class="dfCar">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select></div>
</div>
<div style="padding-top:10px; cursor:pointer; color:blue; text-decoration:underline;" onClick="$('#myForm').BindJson(jsonData, 'df');">
Fill form
</div>
<div style="padding-top:10px; cursor:pointer; color:blue; text-decoration:underline;" onClick="$('#myForm').ClearDataFields('clearMe');">
Clear form
</div>
JavaScript
var jsonString = "{'Name':'Chris Clark','Car':'saab','Check1':true,'Check2':false,'Email':'chris@untrod.com'}";
jsonData = eval("(" + jsonString + ")");
(function ($) {
$.fn.BindJson = function (fieldData, cssClassPrefix) {
var selectorPrefix = " ." + cssClassPrefix,
key = [],
ctl = null,
isTextField = false,
fill = "";
for (key in fieldData) {
if (fieldData.hasOwnProperty(key)) {
ctl = $(selectorPrefix + key, this);
fill = fieldData[key];
if (ctl.length != 0) {
isTextField = (ctl[0].tagName == "DIV" || ctl[0].tagName == "SPAN" || ctl[0].tagName == "LABEL");
if (isTextField) {
ctl.text(fill);
} else if (ctl[0].type == 'checkbox') {
ctl.attr('checked', (fill == true));
} else {
ctl.val(fill);
}
}
}
}
};
})(jQuery);
(function ($) {
$.fn.ClearDataFields = function (clearClass) {
$(":input", this).each(function () {
var type = this.type,
tag = this.tagName.toLowerCase();
if (type == 'text' || type == 'password' || tag == 'textarea' || type == 'hidden') {
this.value = "";
} else if (type == 'checkbox' || type == 'radio') {
this.checked = false;
} else if (tag == 'select') {
this.selectedIndex = 0;
}
});
if (clearClass) {
$("." + clearClass, this).text("");
}
};
})(jQuery);