jQuery: Find All Checked Checkboxes

So this is sort of a repeat of another post, but I figured it has some use on its own.

Say you have this:

  <div>
    <input type="checkbox" name="JqueryIdList" value="1"  />
    <input type="checkbox" name="JqueryIdList" value="2" />
    <input type="checkbox" name="JqueryIdList" value="3" />
    <input type="checkbox" name="JqueryIdList" value="4" />
  </div>
  <div onclick="getIds('JqueryIdList');">
    CLICK
  </div>

And you need the getIds method to find all the checked checkboxes from that markup. Well it’s actually fairly simple, or at least it wil be once I enlighten you. I should get paid for this…

  function getIds(checkList)
  {
    var idList = new Array();
    var loopCounter = 0;
    //find all the checked checkboxes
    jQuery("input[name=" + checkList + "]:checked").each
    (
      function()
      {
        //fill the array with the values
        idList[loopCounter] = jQuery(this).val();
        loopCounter += 1;
      }
    );
    ...
  }

The important part is this:

 jQuery("input[name=" + checkList + "]:checked").

As you can see, it is very simple. Give it the name of the checkboxes, add on the “:checked” and boom you have a list of checked checkboxes. Could it be more simple? I think not.

Tags:

  • wing_hk

    or just

    jQuery(“input[#'checkList']:checked”)

  • wing_hk

    oops my mistake

  • Vincent W

    How would you select them if your checkbox names have square brackets after them, like you would in a list that you submit for update.( ex. randomname[] )