【发布时间】:2014-09-14 20:18:04
【问题描述】:
我将表单保存为 json 对象,在刷新或重新访问页面时我使用它来重建表单。它工作得很好,除了我在定位名称属性后带有“[]”的复选框时遇到问题。
我的对象:{"product":{"checkboxname":["value1","value2"]}}
// Reset form values from json object
$.each(formStateObjects[presentFormElementID], function(name, val){
var $el = $('[name="'+name+'"]');
var type = $el.attr('type');
switch(type){
case 'checkbox':
$el.attr('checked', 'checked'); // Only works for checkboxes with unique name
break;
case 'radio':
$el.filter('[value="'+val+'"]').attr('checked', 'checked');
break;
default:
$el.val(val);
}
});
我需要以某种方式更改我的复选框选择器,或者为具有共享名称的复选框创建一个新选择器。但我不知道怎么做。
---- 编辑:更新了我的代码 -------------------------- ---
我使用下面的代码让它工作,尽管现在它不能确保检查正确的名称。
// Reset form values from json object
$.each(formStateObjects[presentFormElementID], function(name, val){
var $el = $("[name=" + name + "]");
var type = $el.attr('type');
// If we have a checkbox name with many values
if(val instanceof Array) {
checkboxArrayValues = val;
$.each( checkboxArrayValues, function( intValue, currentValue ) {
// Refine the selector checking for name
var $hit = $("[value=" + currentValue + "]");
$hit.prop('checked', true);
});
}
switch(type){
case 'checkbox':
$el.prop('checked', true);
break;
case 'radio':
$el.filter('[value="'+val+'"]').prop("checked", true);
break;
default:
$el.val(val);
}
});
【问题讨论】:
标签: jquery json forms checkbox jquery-selectors