jQuery to limit number of checkboxes checked by User
Many time we need to limit the selection of checkboxes users can select or in other words users are not allowed to select more than a number of checkbox to give their choice. For example, out of all client side script language, user can select maximum three where he is best.
Related Post:
- Check if Checkbox is checked using jQuery
- Validate HTML CheckboxList using jQuery
- Check/Uncheck All Checkboxes with JQuery
As for example, take a look at below HTML checkboxlist.
<input type="checkbox" name="tech" value="jQuery" /> jQuery <br/> <input type="checkbox" name="tech" value="JavaScript" />JavaScript <br/> <input type="checkbox" name="tech" value="Prototype" /> Prototype<br/> <input type="checkbox" name="tech" value="Dojo" /> Dojo<br/> <input type="checkbox" name="tech" value="Mootools" /> Mootools <br/>
And now, you want to restrict user to select only 2 scripting language out of above group. Below jQuery code exactly does the same thing.
$(document).ready(function () { $("input[name='tech']").change(function () { var maxAllowed = 2; var cnt = $("input[name='tech']:checked").length; if (cnt > maxAllowed) { $(this).prop("checked", ""); alert('Select maximum ' + maxAllowed + ' technologies!'); } }); });
The idea is simple. Find out number of checked checkboxes and if they are greater than maximum allowed then alert the user.
Feel free to contact me for any help related to jQuery, I will gladly help you.