Check if at least one checkbox is checked using jQuery

前端 未结 9 1234
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-31 11:31

I have five checkboxes. Using jQuery, how do I check if at least one of them is checked?



<
9条回答
  •  忘掉有多难
    2020-12-31 12:28

    Edit: The original solution in this answer is inefficient and should not be used. Please see the revised solution based on comments and examples from other answers to this question.

    The original (bad) solution follows:

    // DO NOT USE; SEE BELOW
    $('button').click(function () {
      var atLeastOneIsChecked = false;
      $('input:checkbox').each(function () {
        if ($(this).is(':checked')) {
          atLeastOneIsChecked = true;
          // Stop .each from processing any more items
          return false;
        }
      });
      // Do something with atLeastOneIsChecked
    });
    

    The use of .each() is redundant in this example, as .is() can be used directly on the set of objects rather than manually iterating through each one. A more efficient solution follows:

    $('button').click(function () {
      var atLeastOneIsChecked = $('input:checkbox').is(':checked');
      // Do something with atLeastOneIsChecked
    });
    

    Note that one of the comments indicates a strong dislike for $(this).is(':checked'). To clarify, there is nothing wrong with is(':checked') in cases where you are testing a set of objects. That said, calling is(':checked') on a single item is much less efficient than calling .checked on the same item. It also involves an unnecessary call to the $ function.

提交回复
热议问题