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.
See Complete Code
Feel free to contact me for any help related to jQuery, I will gladly help you.