简体   繁体   中英

.is(“:checked”) doesn't work in jQuery

I'm new to jQuery and I need to check if the checkbox is checked. In other posts I saw that I need to use .is(":checked") to solve it, but somehow it doesn't work.

 $('.neutral').on('click', function() { var checkbox = $(this); if (checkbox.is(":checked")) { console.log('checked'); } else { console.log('unchecked'); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" class="neutral" /> 

In this code I have 2 problems and I don't know how to solve it.

  1. When I'm using console.log('checked') outside of the if statement (after checkbox variable) and I click on the checkbox one time, console prints the result 2 times.

  2. I don't know why this if statement doesn't working.

Thank you for your time and help.

checked happens after the change event,just replace click with change.

 $('.neutral').on('change', function() { var checkbox = $(this); if (checkbox.is(":checked")) { console.log('checked'); } else { console.log('unchecked'); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" class="neutral" /> 

I have seen your code, I think you should try

$(document).on("click",".neutral",function() {
        // Write code here
    });

Instead of your code, Replace this code to as i written

$('.neutral').on('click', function() {
     // Code here
});

For more undesirability see here

$(document).ready(function() {
    // This WILL work because we are listening on the 'document', 
    // for a click on an element with an ID of #test-element
    $(document).on("click","#test-element",function() {
        alert("click bound to document listening for #test-element");
    });

    // This will NOT work because there is no '#test-element' ... yet
    $("#test-element").on("click",function() {
        alert("click bound directly to #test-element");
    });

    // Create the dynamic element '#test-element'
    $('body').append('<div id="test-element">Click mee</div>');
}); 

Visit these link that may help you more for your implementation

Statck over flow link

jsFiddle Link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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