简体   繁体   中英

checkbox value checked if its value equals to 1

I want to make checkbox checked if its value == 1 and unchecked if value == 0. please suggest some logic. Thanks in advance who helping me.

<div class="checkbox">
    <label><input type="checkbox" class="preference" value="1" data-value="size1" id="datasize1">A</label>\
</div>\
<div class="checkbox">\
    <label><input type="checkbox" class="preference" value="0" data-value="size2" id="datasize2">B</label>\
</div>\
<div class="checkbox">\
    <label><input type="checkbox" class="preference" value="1" data-value="size3" id="datasize3">C</label>\
</div>\
<div class="checkbox">\
    <label><input type="checkbox" class="preference" value="1" data-value="size4" id="datasize4">D</label>\
</div>\
<div class="checkbox">\
    <label><input type="checkbox" class="preference" value="0" data-value="size5" id="datasize5">E</label>\
</div>\
<div class="checkbox">\
    <label><input type="checkbox" class="preference" value="1" data-value="size6" id="datasize6">F</label>\
</div>\
<div class="checkbox">\
    <label><input type="checkbox" class="preference" value="0" data-value="size7" id="datasize7">G</label>\
</div>

$('.preference').each(function(e){
    if($(this).val() == 1){
        $(this).checked;
    }
});

You were pretty close, but checked attribute is for JS object, not Jquery. For JQuery you set it's attribute "checked" to checked:

$('.preference').each(function(e){
    if($(this).val() == 1){
        $(this).attr("checked", "checked");
    }
});

Here is a JSFiddle

You can use this function

 function isCheckedById(id) { alert(id); var checked = $("input[@id=" + id + "]:checked").length; alert(checked); if (checked == 1) { return false; } else { return true; } } 

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