简体   繁体   English

如何获取复选框的输入值(真/假)

[英]How to get the input value of a checkbox (true/false)

I have this html and I am trying to get the input value of a certain checkbox我有这个 html,我正在尝试获取某个复选框的输入值

    var option = document.createElement('li');
    var checkbox = document.createElement('input');
    var label = document.createElement('label')
    var optionId = "option" + "" + questionNumber + subquestionNumber;
    var checkBoxId = "checkbox" + "" + questionNumber + subquestionNumber;
    var labelId = "label" + "" + questionNumber + subquestionNumber;
    var labelname = "name" + "" + questionNumber + subquestionNumber;
    checkbox.type = "checkbox";
    label.id = labelId;
    label.name= labelname;
    option.id = optionId;
    option.className = "optionName";
    checkbox.id = checkBoxId;
    checkBoxId.htmlFor = option;
    label.appendChild(document.createTextNode('Option ' + subquestionNumber));
    option.appendChild(label); //add `label` to `li`
    option.appendChild(checkbox); //add `checkbox` to `li`
    q.appendChild(option);

    var checkboxes = document.querySelector(labelId);
    document.getElementById("testingBox6").innerHTML = checkboxes;

I want to save the input value to the variable checkboxes我想将输入值保存到变量复选框

Thank you for your time感谢您的时间

With Jquery , it can be simple.使用Jquery可以很简单。 But, you can try this without Jquery但是,你可以在没有Jquery的情况下尝试这个

document.getElementById(checkboxId).checked; document.getElementById(checkboxId).checked;

you can get true/false with checked你可以通过checked得到真/假

for example例如

var checkbox = document.createElement('input');
checkbox.setAttribute("type", "checkbox");

checkbox.addEventListener("change", ()=> {
   console.log(checkbox.checked); // it gives true or false when you clicked
})

甚至你可以使用

document.querySelector('#checkBoxId').checked;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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