[英]How to check radio button based on the name and value?
我的表单上有4组不同的单选按钮。 每个组都有不同的名称集。 我使用JSON对象存储数据。 在遍历数据时,我使用前面带有附加单词的键。 这将为我提供该数据集的每个表单元素的名称。 我成功填充了文本和复选框输入字段,但仍然可以使用单选按钮。 这是我的JSON数据:
var jsonData = {
myForm:{"hs_mask":"Yes","name":"John Miller","hs_cktr":"Yes"}
}
这是填充表单字段的逻辑:
$.each(jsonData[jsonKey], function(index, element) {
var frmElementName = $('[name="'+'frm'+index.toLowerCase()+'"]');
var frmElementId = $('#frm'+index.toLowerCase());
var frmVal = $.trim(decodeURIComponent(element))
if(frmElementName.attr('type') == 'text'){
frmElementId.val(frmVal);
}else if(frmElementName.attr('type') == 'checkbox'){
(frmVal == 'Yes') ? frmElementId.attr('checked',true) : frmElementId.attr('checked',false);
}else if(frmElementName.attr('type') == 'radio'){
$('input[name="'+'frm'+index.toLowerCase()+'"][value="' + frmVal + '"]').prop('checked', true);
}
});
我已经尝试了上面的代码,但是没有选中单选按钮。 如您所见,对于文本和复选框类型,我使用ID填充字段,但对于单选按钮,我使用元素名称。 如果有人看到我的代码在哪里中断,请告诉我。 谢谢。
今天,我面临着类似的问题。 这是我的解决方案:
function jsonToForm(json) { // populates form elements with JSON data
for (var x in json) { // JSON iteration
var id = x; // in my original code x has to be processed to match form and object names
var element = document.getElementById(id);
if (element) { // if JSON key corresponds to a non radio button (unique id) form element
element.value = json[x]; // updates form values
} else if (document.getElementsByName(id)) { // for radio buttons the name attribute is used as JSON key won't match separate radio button id's.
var radios = document.getElementsByName(id);
for (var i = 0; i < radios.length; i++) { // radio button iteration
if (radios[i].value == json[x]) {
radios[i].checked=true;
break;
}
}
}
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.