简体   繁体   中英

How to check that at least one checkbox must be selected in php usnig jquery

How can I check that at least one checkbox must is selected in php using jQuery? I want to show an alert if the user does not mark any checkbox.

Here's the current code that I'm testing, but it always gives an alert.

HTML:

<div class="form">
  <form id="dddd" action="action.php" method="post" enctype="multipart/form-data">
    <div>
      <label><input type="checkbox" name="checkboxlist[]" value="a" checked> a</label>
      <label><input type="checkbox" name="checkboxlist[]" value="b" checked> b</label>
      <label><input type="checkbox" name="checkboxlist[]" value="c" checked> c</label>
      <label><input type="checkbox" name="checkboxlist[]" value="d" checked> d</label>
      <label><input type="checkbox" name="checkboxlist[]" value="e" checked> e</label>
      <label><input type="checkbox" name="checkboxlist[]" value="f" checked> f</label>
      <label><input type="checkbox" name="checkboxlist[]" value="g" checked> g</label>
    </div>
    <p>
      <button type="submit" class="btn btn-primary">Start</button>    
    </p>
  </form>

JavaScript:

$(document).ready(function() {
  $("form#dddd").submit (function() {
    if ($('.checkboxlist').is(":checked") == false) {
      alert("Please select at least one item !");
      return false;
    }
    return true;
  });
});

Edit based on responses and running Working code

<script>
    $(document).ready(function() {
        $("form#dddd").submit (function() {
            if($('input[type="checkbox"]:checked').length) {
                return true;
            } else {
                alert("Please select at least one item !");
                return false;
            }           
        });
    });
</script>

Check the length of :checked checkbox like following

if($('input[type="checkbox"]:checked').length) {
    // do your stuff
}

instead of

if($('.checkboxlist').is(":checked") == false) {

}

Try this :

if($('input[name^=checkboxlist]:checked').length > 0) {
    alert("success");
} else {
     alert("error");
     return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM