How to check if a checkbox is checked using jQuery?

I am trying to enable the click function if the user has checked the box on the page. Otherwise, I want to add the class to the #additional_foreign button.

I think I'm 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 box, it does not allow the click function, and when I clear the box, it also does not 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>
+3
source share
2 answers

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

If this was my code, I would 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>
+8

, , , . , , , :

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

Source: https://habr.com/ru/post/1731496/


All Articles