简体   繁体   English

如何检查复选框是否被选中?

[英]How to check whether a checkbox is checked?

Here is something I have now: I've got a checkbox, which I need to verify whether it is selected. 这是我现在拥有的东西:我有一个复选框,需要确认是否已选中它。

<input type="checkbox" name="person_info_check" value="0" &nbps>Read and agree!</input>

But when I tried to use the way I had searched through the Internet, I found I couldn't catch the checkbox and thus verify. 但是,当我尝试使用通过Internet进行搜索的方式时,发现无法抓住复选框进行验证。

This is how I grab the checkbox: 这是我抓取复选框的方式:

        if($('#person_info_check').is(':checked')){
            if(confirm("Are you sure to submit?")){
                return true;
            }
            else return false;
        }
        else{
            alert("Please read the file and agree the statement!");
            return false;
        }

And I've also tried this: 我也尝试过这样:

        var checkbox = document.getElementsByName("person_info_check");

        if(checkbox[0].checked==false){
            alert("Please read the file and agree the statement!");
            return false;
        }

You are using $('#person_info_check') that is actually a jQuery ID Selected while in your HTML you specified the name="person_info_check" so your element is not getting selected. 您正在使用$('#person_info_check')实际上是一个选定的jQuery ID,而在HTML中您指定了name="person_info_check"这样就不会选择您的元素。

Try specifying the id="person_info_check" in your checkbox element. 尝试在复选框元素中指定id="person_info_check" Most of the jQuery code should work. 大多数jQuery代码都可以正常工作。

Or you can use the JQuery name selector. 或者,您可以使用JQuery名称选择器。

$("input[value='person_info_check]")

The problem is that person_info_check is not the id of your input but the name attribute. 问题在于person_info_check不是您输入的ID,而是name属性。 You should use this: $("input[name='person_info_check']").is(':checked'); 您应该使用以下命令: $("input[name='person_info_check']").is(':checked');

There are major errors in your code such as: 您的代码中存在主要错误,例如:

  1. Input type checkbox does not require any value tag 输入类型checkbox不需要任何值标签
  2. Input type does not require to have a closing tag 输入类型不需要结束标记
  3. Input type does not entertain the HTML text; 输入类型不接受HTML文本; it only can have value or checked status according to the tag type. 根据标签类型,它只能具有值或已检查状态。

More details of the input tag can be found here . 输入标签的更多详细信息可以在这里找到。 An example of code is as follows: 代码示例如下:

 var checkbox = document.getElementById("che"); if (checkbox.checked == true) { alert('I am checked') } 
 <input type="checkbox" name="person_info_check" id='che' checked/> <label for='che'>I am checkbox</label> 

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

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