如何使用JavaScript检查/不检查复选框?


当前回答

我们可以这样选中一个粒子复选框,

$('id of the checkbox')[0].checked = true

然后取消检查,

$('id of the checkbox')[0].checked = false

其他回答

function setCheckboxValue(checkbox,value) {
    if (checkbox.checked!=value)
        checkbox.click();
}

对于单个检查,请尝试

myCheckBox.checked = 1 <input type="checkbox" id="myCheckBox">给她打电话

对于多重尝试

document.querySelectorAll(“.imChecked”)。forEach (c = > c.checked = 1) 买酒:<input type="checkbox" class="imChecked"><br> 播放流畅的爵士音乐:<input type="checkbox"><br> 剃须:<input type="checkbox" class="imChecked"><br>

Javascript:

// Check
document.getElementById("checkbox").checked = true;

// Uncheck
document.getElementById("checkbox").checked = false;

jQuery 1.6 (+):

// Check
$("#checkbox").prop("checked", true);

// Uncheck
$("#checkbox").prop("checked", false);

jQuery (1.5 -):

// Check
$("#checkbox").attr("checked", true);

// Uncheck
$("#checkbox").attr("checked", false);

使用vanilla js:

//for one element: 
document.querySelector('.myCheckBox').checked = true  //will select the first matched element
document.querySelector('.myCheckBox').checked = false//will unselect the first matched element

//for multiple elements:
for (const checkbox of document.querySelectorAll('.myCheckBox')) {
//iterating over all matched elements

checkbox.checked = true //for selection
checkbox.checked = false //for unselection
}

检查:

document.getElementById("id-of-checkbox").checked = true;

取消:

document.getElementById("id-of-checkbox").checked = false;