Javascript - 复选框选中条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23966716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:54:05  来源:igfitidea点击:

Javascript - Checkbox checked condition

javascript

提问by Anup

I have a input checkbox, i want to run different block of code, when checkbox is ticked & vice versa.

我有一个输入复选框,我想运行不同的代码块,当复选框被勾选时,反之亦然。

function checkboxEvent(){
    if checked{ ....Run this block  }
    else { ....Run this block  }
}

How to identify in function whether checkbox is checked or not?

如何在函数中识别复选框是否被选中?

回答by Amit Joki

Like this:

像这样:

if(document.getElementById('id of the check box here').checked){
    // it is checked. Do something
}
else{
    // it isn't checked. Do something else
}   

.checkedproperty returns a booleanindicating whether the element is checked or not.

.checked属性返回一个boolean指示元素是否被检查。

回答by Harjeet Singh

its very easy to find checked property, just use below code

很容易找到检查的属性,只需使用下面的代码

if(  $('input[name="transport"]').is(':checked') ) {
            alert('checked');
alert($(this).attr('id'));//To get ID of checkBox
        }

回答by Sumit Tyagi

you can check check box value as follows

您可以检查复选框值如下

document.getElementById("myCheck").checked

So your function would be something like ..

所以你的功能将类似于 ..

function checkboxEvent(){
    if (document.getElementById("myCheck").checked){ ....Run this block  }
    else { ....Run this block  }
}

回答by Gaurang Tandon

You might want to check the checked property when the check box is clicked, do:

您可能希望在单击复选框时检查选中的属性,请执行以下操作:

// onchange event listens when the checkbox's state is changed
document.getElementById('box').onchange = function(){
    if(this.checked) alert("y");
    else alert("no");
};

DEMO

演示

.checkedis a boolean indicating state of checkbox.

.checked是一个布尔值,指示复选框的状态。

回答by codebased

< input type="checkbox id="remember" >

< input type="checkbox id="记住" >

<script>

var remember = document.getElementById('remember');
    if (remember != null && remember.checked){
        alert("checked") ;
    }else{
        alert("You didn't check it! Let me check it for you.")
    }

</script>

回答by Hristo Georgiev

Try this :

试试这个 :

function checkboxEvent() {

    var boxes = document.getElementsByName("chkbox");

    for (i = 0; i < boxes.length; i++) {
        if (boxes[i].checked) {


        console.log(" Checked!");

    } else {
        console.log("not checked");

    }

}

}

The forloop will look up through all of your checkboxes and see if they are checked.

for循环将查找通过所有的复选框,看他们是否被选中。

Alternatively, you can use .hasAtrribute.You can find more info about .hasAttributehere

或者,您可以使用.hasAtrribute.You can find more info about .hasAttributehere