jQuery see if any or no checkboxes are selected

前端 未结 8 1676
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 13:41

I know how to see if an individual checkbox is selected or not.

But Im having trouble with the following - given a form id I need to see if any of the check

相关标签:
8条回答
  • 2020-12-02 14:21

    This is what I used for checking if any checkboxes in a list of checkboxes had changed:

    $('input[type="checkbox"]').change(function(){ 
    
            var itemName = $('select option:selected').text();  
    
             //Do something.
    
    });     
    
    0 讨论(0)
  • 2020-12-02 14:26

    JQuery .is will test all specified elements and return true if at least one of them matches selector:

    if ($(":checkbox[name='choices']", form).is(":checked"))
    {
        // one or more checked
    }
    else
    {
        // nothing checked
    }
    
    0 讨论(0)
  • 2020-12-02 14:34

    You can use something like this

    if ($("#formID input:checkbox:checked").length > 0)
    {
        // any one is checked
    }
    else
    {
       // none is checked
    }
    
    0 讨论(0)
  • 2020-12-02 14:34

    Without using 'length' you can do it like this:

    if ($('input[type=checkbox]').is(":checked")) {
          //any one is checked
    }
    else {
    //none is checked
    }
    
    0 讨论(0)
  • 2020-12-02 14:36

    You can do this:

      if ($('#form_id :checkbox:checked').length > 0){
        // one or more checkboxes are checked
      }
      else{
       // no checkboxes are checked
      }
    

    Where:

    • :checkbox filter selector selects all checkbox.
    • :checked will select checked checkboxes
    • length will give the number of checked ones there
    0 讨论(0)
  • 2020-12-02 14:37

    You can do a simple return of the .length here:

    function areAnyChecked(formID) {
      return !!$('#'+formID+' input[type=checkbox]:checked').length;
    }
    

    This look for checkboxes in the given form, sees if any are :checked and returns true if they are (since the length would be 0 otherwise). To make it a bit clearer, here's the non boolean converted version:

    function howManyAreChecked(formID) {
      return $('#'+formID+' input[type=checkbox]:checked').length;
    }
    

    This would return a count of how many were checked.

    0 讨论(0)
提交回复
热议问题