Home > Article > Web Front-end > jQuery automatically assigns values to form elements based on json objects
In order to improve the development efficiency of front-end partners, we created a wheel that automatically assigns values based on the json object according to the name attribute of the form element
json2form:function(obj){ var nodeParent = null; var value = undefined; var $el = null; var nodeName = ""; for(var i in obj){ value= obj[i] ; if(value === undefined || value===null){ continue; } if(typeof value == 'object'){ nodeParent=obj.nodeParent; value.nodeParent=nodeParent?nodeParent+"."+i : i; if(value instanceof Array){ for(var mm=0;mm<value.length;mm++){ var ms=value[mm]; if(typeof ms == 'object'){ nodeParent=ms.nodeParent; ms.nodeParent=ms.nodeParent?ms.nodeParent+"."+i+"["+mm+"]":i+"["+mm+"]"; arguments.callee(ms); } } $el=$("[name='"+i+"']"); if($el.is(":checkbox")){ $el.each(function(){ if($(this).val() == value){ $(this).prop("checked",true); } }) } else if($el.is(":radio")){ $el.each(function(){ if($(this).val() == value){ $(this).prop("checked",true); } }) } }else{ //递归 arguments.callee(value); } } else{ nodeName=obj.nodeParent?obj.nodeParent+"."+i : i ; $el=$("[name='"+nodeName+"']"); if($el.length > 0){ // console.log("匹配数据名称:"+nodeName+"值:"+value); if($el.is(":text")||$el.attr("type")=="hidden"){ if($el.data("money") && $el.data("money") == "money"){ value = outputdollars(value); } $el.val(value); }else if($el.is(":radio")){ $el.each(function(){ if($(this).val()==value){ $(this).prop("checked",true); } }) } else if($el.is("select")){ $el.find("option").filter(function(){return $(this).val() == obj[i];}).prop("selected",true); }else if($el.is("textarea")){ $el.val(value) } } } } }
Note: The name of the form is consistent with the attribute name of the json object, and the inheritance chain is maintained. For example, input name='a.b.c' represents the c attribute of the b attribute in the a attribute in the json object.