I have an object like this:
var settings = {
Name: "Fairy Tail",
Feature:
{
Translate: true,
Share: true
}
}
And a form
<form>
<input type="text" name="Name" />
<input type="ch开发者_如何学Goeckbox" name="Feature.Translate" />
<input type="checkbox" name="Feature.Share" />
</form>
How can I make the object fill the form "automatically" (without setting the value of each field by hand)?
You can do it this way (jsfiddle for a more sophisticated example), assuming you have settings
variable set first:
var assignValue = function(n, v){
var field = jQuery('form input[name="'+n+'"]');
if (field.attr('type')=='text'){
field.val(v);
} else if (field.attr('type')=='checkbox') {
field.prop('checked',v);
}
}
var assignSettings = function(list, prefix){
if (typeof prefix != 'undefined'){
prefix += '.';
}else{
prefix = '';
}
for (item in list){
if ((typeof list[item]=='string')||(typeof list[item]=='boolean')){
assignValue(prefix+item,list[item]);
}else if(typeof list[item]=='object'){
var n1 = item;
assignSettings(list[n1],prefix+n1);
}
}
}
assignSettings(settings);
And this solution is not as limited as other solutions in the versions I have seen so far - it supports the case you have given and can be easily expanded to support different types of fields and more levels.
var inputs = $('form input[type="checkbox"]');
$.each(settings.Feature, function(key, val) {
inputs.filter('[name="Feature.' + key + '"]')[0].checked = val;
});
Example: http://jsfiddle.net/9z928/
If you also wanted the text field filled in:
var inputs = $('form input');
inputs.first().val( settings.Name );
$.each(settings.Feature, function(key, val) {
inputs.filter('[name="Feature.' + key + '"]')[0].checked = val;
});
Example: http://jsfiddle.net/9z928/1/
Might be worth giving this a try: http://www.keyframesandcode.com/resources/javascript/jQuery/demos/populate-demo.html
You can use this JavaScript library for mapping Obeject to form fields name and vice versa. Object-Form-Mapping
精彩评论