Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

javascript - 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.

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.

<input id="foreign_checkbox" type="checkbox" />
<span id="additional_foreign">Click Me</span>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try using $('#foreign_checkbox').is(":checked") - rest of the code looks fine

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...