Search code examples
javascriptjquerypageloadchecked

How to tell what checkboxes are checked on page load?


I already have a change event/listener going on, but this doesn't do anything when someone refreshes the page...etc (page load) and there are already checked checkboxes.

How can I check to see if ANY checkboxes are checked on page load, and get their name/value (whatever)?

Example: I check to see if ANY checkboxes in a specific DOM element are checked like so:

if($("#allocation input:checkbox").is(':checked')){
    console.log("something is checked");
}

But how can I actually get the id's of the ones that are checked upon page load?

Something like a $this.id inside of the above? (but that doesn't work of course).

Or can you tie an event.target into the above is.('checked') conditional somehow?

Again, I already have something in place for the .change() (user interaction) portion, but if a checkbox is checked and someone reloads the page, the checkbox is still checked (and I need to cater to that still).

My final solution here: (similar/same as suggested below)

KEY.. use the 'each' function..

//on page load
                    $('#allocation input:checked').each(function() {
                        if($(this).is(':checked')){
                            //console.log("CB CHECK: " + $(this).attr('id'));
                            var targetID = $(this).attr('id');
                            $('#' + targetID + 'amount').prop('disabled', false);
                        }
                    });

Solution

  • Combine the selectors "#allocation input:checked" (or "#allocation input:checkbox:checked") which will give you an array of all checkboxes that are checked. Then loop through them with each() and you can get the id with this.id.

    Put the entire code in a self-executing function (function() {...})(); at the bottom of your code or at least bellow all the checkboxes. Something like this:

    (function() {
      $("#allocation input:checked").each(function() {
        console.log(this.id + " is checked")
      });
    })();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <div id="allocation">
      <input type="checkbox" id="chk1" checked="checked" /> Option 1
      <input type="checkbox" id="chk2" /> Option 2
      <input type="checkbox" id="chk3" /> Option 3
      <input type="checkbox" id="chk4" checked="checked" /> Option 4
      <input type="checkbox" id="chk5" checked="checked" /> Option 5
    </div>