简体   繁体   中英

How to check if number of checked checkbox is multiply of 3 using jquery?

In my ul li tags and i want to when sumbit pressed, check if number of checked checkbox isn't muliply of 3, display alert. How i achive this?

<ul>
    <li><input type="checkbox" />a</li>
    <li><input type="checkbox" />b</li>
    <li><input type="checkbox" />c</li>
    <li><input type="checkbox" />d</li>
    <li><input type="checkbox" />e</li>
    <li><input type="checkbox" />f</li>
</ul>
<input type="submit" value="go" />

Get length of checked checkbox and use the % (modulus) operator to check number is multiple of 3 . If number is multiple of 3 result will be 0 .

 $("button").click(function(){ var length = $("ul :checkbox:checked").length; if (length == 0 || length % 3 != 0) console.log("Select multiply of 3"); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li><input type="checkbox" />a</li> <li><input type="checkbox" />b</li> <li><input type="checkbox" />c</li> <li><input type="checkbox" />d</li> <li><input type="checkbox" />e</li> <li><input type="checkbox" />f</li> </ul> <button>Continue</button>

you can just check the number of selected checkbox using

$("#chkboxes").find("input:checked").length;

your html

<ul id="chkboxes">
  <li><input type="checkbox" />a</li>
  <li><input type="checkbox" />b</li>
  <li><input type="checkbox" />c</li>
  <li><input type="checkbox" />d</li>
  <li><input type="checkbox" />e</li>
  <li><input type="checkbox" />f</li>
</ul>
<button type="button" onclick="checkvalues()">Submit</button><span id="msg"></span>

Js

function checkvalues(){
var count = $("#chkboxes").find("input:checked").length;

$("#msg").text(count>0 && count%3==0?"multiple of 3 selected!":"please select multiple of 3");

}

You can check the fiddle here

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