Can I use jQuery to check whether at least one checkbox is checked?

前端 未结 6 1588
礼貌的吻别
礼貌的吻别 2020-12-01 02:08

I have the following HTML form which can have many checkboxes. When the submit button is clicked, I want the user to get a javascript alert to check at least one checkbox if

相关标签:
6条回答
  • 2020-12-01 02:14
    $("#frmTest").submit(function(){
        var checked = $("#frmText input:checked").length > 0;
        if (!checked){
            alert("Please check at least one checkbox");
            return false;
        }
    });
    
    0 讨论(0)
  • 2020-12-01 02:25
    $("#show").click(function() {
        var count_checked = $("[name='chk[]']:checked").length; // count the checked rows
            if(count_checked == 0) 
            {
                alert("Please select any record to delete.");
                return false;
            }
            if(count_checked == 1) {
                alert("Record Selected:"+count_checked);
    
            } else {
                alert("Record Selected:"+count_checked);
              }
    });
    
    0 讨论(0)
  • 2020-12-01 02:31
    $('#frmTest input:checked').length > 0
    
    0 讨论(0)
  • 2020-12-01 02:31

    $('#fm_submit').submit(function(e){
        e.preventDefault();
        var ck_box = $('input[type="checkbox"]:checked').length;
        
        // return in firefox or chrome console 
        // the number of checkbox checked
        console.log(ck_box); 
    
        if(ck_box > 0){
          alert(ck_box);
        } 
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form name = "frmTest[]" id="fm_submit">
      <input type="checkbox" value="true" checked="true" >
      <input type="checkbox" value="true" checked="true" >
      <input type="checkbox" >
      <input type="checkbox" >
      <input type="submit" id="fm_submit" name="fm_submit" value="Submit">
    </form>
    <div class="container"></div>

    0 讨论(0)
  • 2020-12-01 02:36
    if(jQuery('#frmTest input[type=checkbox]:checked').length) { … }
    
    0 讨论(0)
  • 2020-12-01 02:36
    $('#frmTest').submit(function(){
        if(!$('#frmTest input[type="checkbox"]').is(':checked')){
          alert("Please check at least one.");
          return false;
        }
    });
    

    is(':checked') will return true if at least one or more of the checkboxes are checked.

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