[英]Set checkbox is checked or not from json data
I have checkbox and I want to change it's value using jquery depending on values come by json data I restore string in database that determine the value of every html element like this 我有复选框,我想使用jQuery更改它的值,具体取决于json数据的值,我在数据库中恢复了字符串,该字符串确定了每个html元素的值,像这样
bandwidthcap:=false,download:=,upload:=,restrict:=true
the bandwidthcap is toggle checkbox but the program every time set it as checked even if the value is false as you can see. 带宽上限为切换复选框,但是程序每次都将其设置为选中状态,即使您看到的值为false也不例外。 this is the jquery code to get json data and set it to html elements 这是获取json数据并将其设置为html元素的jquery代码
var jsonData = $.ajax({
url: "Save.php?id=gettallemplate&tempname="+name,
dataType: "json",
async: false
}).responseText;
//}
//alert(jsonData);
var obj = $.parseJSON(jsonData);
var array = obj['data'].split(",");
$.each(array,function(i){ var array2 = array[i].split(":=");
$('#'+array2[0]).val(array2[1]);
$('#'+array2[0]).attr('checked', array2[1]);
});
array2[0]
contain the element ID and the array2[1]
contain value for bandwidthcap checkbox $('#bandwidthcap').attr('checked',false)
but it give checked I searched alote without result array2[0]
包含元素ID,而array2[1]
包含array2[1]
复选框$('#bandwidthcap').attr('checked',false)
但它给出了检查结果,我搜索了alote却没有结果
true
and false
are being treated as string
and hence you can't use/treat them as boolean. true
和false
被视为string
,因此您不能将它们用作布尔值。
You need to check: 您需要检查:
var flag = (array2[1] === "true");
And use flag
to set checkbox as checked or unchecked: 并使用flag
将复选框设置为选中还是未选中:
var someData = 'bandwidthcap:=false,download:=,upload:=,restrict:=true'; var array = someData.split(","); $.each(array, function(i) { var array2 = array[i].split(":="); var flag = (array2[1] === "true"); $('#' + array2[0]).val(array2[1]); $('#' + array2[0]).attr('checked', flag); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='checkbox' id='bandwidthcap' /> <input type='checkbox' id='download' /> <input type='checkbox' id='upload' /> <input type='checkbox' id='restrict' />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.