Manoj Manoj - 2 months ago 23
jQuery Question

jQuery select multiply of 3

In my Ul li i want to select only muliply of 3, otherwise it will show alert msg. 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"/>


UPDATE : By multiple of 3 its means total number of selected checkbox should be in multiple of 3.

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>