gpt4 book ai didi

javascript - 通过循环从 JSON 选择适当的单选按钮

转载 作者:太空宇宙 更新时间:2023-11-04 16:29:54 27 4
gpt4 key购买 nike

我正在获取 JSON,并且正在使用相关数据填充表单的控件。除了单选按钮之外,所有控件都工作正常。在我的数据库中,我将单选按钮的值保存为 BIT

因此,我正在解析 JSON 并循环每个控件并为其分配值。然而,我似乎在单选按钮上做了一些错误的事情(可能是 case 语句或我的 html)。有什么想法吗?

  • 我使用的是 jQuery 1.9

HTML

            <div class="col-sm-5">
<label class="radio-inline">
<input type="radio" class="myform" value="1" name="testx">
YES
</label>
<label class="radio-inline">
<input type="radio" class="myform" value="0" name="testx">
NO
</label>

</div>

<div class="col-sm-5">
<label class="radio-inline">
<input type="radio" class="myform" value="1" name="highdanger">
YES
</label>
<label class="radio-inline">
<input type="radio" class="myform" value="0" name="highdanger">
NO
</label>
</div>

我的循环

     $.ajax({
type: "GET",
cache: false,
url: serviceUrl + "/ModuleTask/GetExamination" + qstring,
// beforeSend: sf.setModuleHeaders,
contentType: "application/json; charset=utf-8"
}).done(function (result) {
var oResult = JSON.parse(result);

// reset form values from json object
$.each(oResult, function (name, val) {
var $el = $('[name="' + name + '"]'),
type = $el.attr('type');

switch (type) {
case 'checkbox':
$el.attr('checked', 'checked');
break;
case 'radio':
// $el.filter('[value="' + val + '"]').attr('checked', 'checked');
//$el.attr('checked', 'checked');
// $el.prop("checked", val);
//$el.filter('[value="' + val + '"]').prop("checked", true);
// $el.filter('[value="' + true + '"]').val(1);
$el.filter('[value="' + val + '"]').prop("checked", true);
break;
default:
$el.val(val);
}
});


}).fail(function (xhr, result, status) {
alert(result);
});

AJAX 响应

{"ExaminationID":1,"UserID":44,"PortalID":0,"bloodcholisterol":1,"bloodldl":2,"bloodhdl":3,"bloodtriglycerides":4,"bloodglucose":5,"bodyweight":6,"bodyheight":7,"bodycircumference":8,"bodyexaminer":"DD","bodycomments":"a1","pressurestarttime":null,"pressureone":100,"pressuretwo":200,"pressurethree":300,"pressureexaminer":"B","pressurecomments":"B1","FileID":null,"agogiartiriakipiesi":null,"agogilipidia":null,"agogisakxarodidiaviti":null,"examinationcomments":"c1","highdanger":false,"sistaseis":"no sistaseis","axiologisiexaminer":"XH"}

最佳答案

在您的 radio 开关案例中,您需要首先将 boolean 转换为整数。按此整数值进行过滤并将checked 属性更改为true。尝试这样的事情...

case 'radio':
var i = val ? 1 : 0;
$el.filter("[value='"+ i +"']").attr("checked", true);
break;

这是一个JSFiddle来演示。

关于javascript - 通过循环从 JSON 选择适当的单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39906566/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com