Manoj Manoj - 2 months ago 6
HTML Question

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" />

Answer

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>

Comments