简体   繁体   中英

jQuery: Is CheckBox checked on page load?

I have this JavaScript code:

$(document).ready(function(){
    $('#CustomersResellers').hide();

    $('input.ShowResellerAccounts').on('click', function(){
        if($(this).is(':checked')){
            alert('checked');
        }
    });
});

which shows the alert when I check the box, but if the box is already checked on page load, it does not show the alert.

Lets update the function:

var alertChecked = function() {
  if($(this).is(':checked')){
    alert('checked');
  }
}

// invoke the function when clicked
$('input.ShowResellerAccounts').on('click', alertChecked); 

//invoke the function for all matching elements
$('input.ShowResellerAccounts').each(alertChecked); 

Of course it should not be shown, because nowhere in your code you attached event handler when checkbox is checked. So just add a hanlder, when checkbox is checked, like this

$(document).ready(function(){
    $('#CustomersResellers').hide();

    // Define a handle to avoid duplication 
    function handler(){
      alert('checked');   
    }

    if ($('input.ShowResellerAccounts').is(':checked')){
       handler();
    }

    $('input.ShowResellerAccounts').on('click', function(){
        if($(this).is(':checked')){
            handler();
        }
    });
});

This is exactly the behavior I would expect. if $(this).is(':checked') means 'if this checkbox is checked' - then show the alert. But when you click to uncheck the box ( on('click'...) ), it becomes unchecked and alert does not show.

Just make a very slight change and you're there:

$(document).ready(function(){
    $('#CustomersResellers').hide();

    $('input.ShowResellerAccounts').on('click', function(){
        if($(this).is(':checked')){
            alert('checked');
        }
    })
    .trigger('click'); //<<<===== This is all you need to add :)
});

Usually you would append a similar event trigger at the end of event listener code:

$('selector').on('event', handler).trigger('event'); 

In your case you can use .trigger('click') or just .click() . Very clean and straight forward :)

SPECIAL NOTE

And since you're dealing with a checkbox (and not a button) I would favor the change event over the click event.

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