Check if at least one checkbox is checked using jQuery

前端 未结 9 1160
爱一瞬间的悲伤
爱一瞬间的悲伤 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:15
    var atLeastOneIsChecked = $('input[name="service[]"]:checked').length > 0;
    
    0 讨论(0)
  • 2020-12-31 12:16

    This should do the trick:

    function isOneChecked() {
        return ($('[name="service[]"]:checked').length > 0);
    }
    
    0 讨论(0)
  • 2020-12-31 12:18
    var checkboxes = document.getElementsByName("service[]");
    if ([].some.call(checkboxes, function () { return this.checked; })) {
      // code
    }
    

    What you want is simple, get all the elements with the name, then run some code if some of those elements are checked.

    No need for jQuery.

    You may need an ES5 shim for legacy browsers though

    0 讨论(0)
  • 2020-12-31 12:20

    You can do the following way. Initially set a variable, lets say checked as false. Then set it to true if the following condition met. Use an if statement to check the variable. Take note: Here submit is the id of the button, main is the id of the form.

    $("#submit").click(function() {
      var checked = false;
      if (jQuery('#main input[type=checkbox]:checked').length) {
        checked = true;
      }
      if (!checked) {
        //Do something
      }
    });

    0 讨论(0)
  • 2020-12-31 12:22

    You should try like this....

    var checkboxes = $("input[type='checkbox']"),
    submitButt = $("input[type='submit']");
    
    checkboxes.click(function() {
    submitButt.attr("disabled", !checkboxes.is(":checked"));
    

    });

    0 讨论(0)
  • 2020-12-31 12:27

    you need to check if checkbox is checked or not.

    $("#select_all").click(function(){
               var checkboxes = $("input[type='checkbox']");
               if(checkboxes.is(":checked"))
                   alert("checked");
               else
                   alert("select at least one;      
    
                });
    
    0 讨论(0)
提交回复
热议问题