简体   繁体   English

如何检查是否使用JQuery选中了复选框?

[英]How do I check if a checkbox is checked with JQuery?

I am trying to allow a click function if the user has checked a checkbox on the page. 如果用户选中了页面上的复选框,我试图允许点击功能。 Otherwise, I want to add a class to the #additional_foreign button. 否则,我想在#additional_foreign按钮中添加一个类。

I think I am close, but it doesn't seem to be working. 我想我很接近,但似乎没有用。 Here is my code: 这是我的代码:

if($('#foreign_checkbox').attr('checked')) { 
    $('#additional_foreign').click(function() {
        alert('This click function works');
    });
} else {
    $('#additional_foreign').addClass('btn_disable');   
}

When I check the checkbox, it doesn't allow the click function and when I uncheck the checkbox, it also doesn't add the class as it should. 当我选中复选框时,它不允许单击功能,当我取消选中该复选框时,它也不会按原样添加该类。

What am I doing wrong? 我究竟做错了什么?

EDIT:Here is my HTML for clarification. 编辑:这是我的HTML澄清。

<input id="foreign_checkbox" type="checkbox" />
<span id="additional_foreign">Click Me</span>

try using $('#foreign_checkbox').is(":checked") - rest of the code looks fine 尝试使用$('#foreign_checkbox').is(":checked") - 其余代码看起来很好

If this was my code I'd do something like this to make it work: 如果这是我的代码,我会做这样的事情让它工作:

<input id="foreign_checkbox" type="checkbox" />
<span style='display:none' id="additional_foreign">Click Me</span>

<script type="text/javascript">
    $(document).ready(function() {

        $("#foreign_checkbox").click(function() {
            if($('#foreign_checkbox').is(':checked')) { 
                $('#additional_foreign').show();
            } else {
                $('#additional_foreign').hide();
            }
        });

        $('#additional_foreign').click(function() {
            alert('This click function works');
        });
    });
</script>

The problem is that the code doesn't run continually, only when the page loads, when all the boxes are unchecked. 问题是代码不会连续运行,只有当页面加载时,才会取消选中所有框。 You need an action that fires when the box is checked or unchecked, which adds an action or a class to the button: 您需要在选中或取消选中该框时触发的操作,这会向该按钮添加操作或类:

$('#foreign_checkbox').change(function(){
    if (this.checked){
        $('#additional_foreign').click(function() {
           doSomething();
        });
    } else {
        $('#additional_foreign').addClass('btn_disable');
    }   
});

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

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