简体   繁体   中英

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

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. this is the jquery code to get json data and set it to html elements

 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

true and false are being treated as string and hence you can't use/treat them as boolean.

You need to check:

var flag = (array2[1] === "true");

And use flag to set checkbox as checked or unchecked:

 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' /> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM