nuisance nuisance - 4 months ago 12
HTML Question

How to stop checking checkboxes after a number of checkboxes have been checked for a few questions

I know how to stop checking checkboxes after a number of checkboxes have been checked. My problem is how to do this for a few questions, each of which can have multiple checkboxes ticked.

My code is at jsFiddle and visible below:

Code snippet




$('input[type="checkbox"]').click(function(event) {
if (this.checked && $('input:checked').length > 3) {
event.preventDefault();
alert('You\'re not allowed to choose more than 3 boxes');
}
});

<p><strong><em>Question 1 </em></strong></p>
<br></br><br></br>
<div id="Checklist1B10">
<table>
<tr>
<td width="1%">
<input type="checkbox" name="QUESTION1" id="QUESTION1A1"/>
</td>
<td width="15%">
<label for="QUESTION1A1">Strongly Disagree4</label>
</td>
<td width="1%">
<input type="checkbox" name="QUESTION1" id="QUESTION1A2"/>
</td>
<td width="15%">
<label for="QUESTION1A2">Disagree</label>
</td>
<td width="1%">
<input type="checkbox" name="QUESTION1" id="QUESTION1A3"/>
</td>
<td width="15%">
<label for="QUESTION1A3">Undecided</label>
</td>
</tr>
<tr>
<td width="1%">
<input type="checkbox" name="QUESTION1" id="QUESTION1A4"/>
</td>
<td width="15%">
<label for="QUESTION1A4">Agree</label>
</td>
<td width="1%">
<input type="checkbox" name="QUESTION1" id="QUESTION1A5"/>
</td>
<td width="15%"><label for="QUESTION1A5">Strongly Agree </label>
</td>
</tr>
</table>
</div>
<p><strong><em>Question 2 </em></strong></p>
<br></br> <br></br>
<div class="c7" id="Checklist2B10">
<input type="checkbox" name="QUESTION2" id="QUESTION2A1"/>
<label for="QUESTION2A1">Monday</label>
<br></br>
<input type="checkbox" name="QUESTION2" id="QUESTION2A2"/>
<label for="QUESTION2A2">Tuesday</label>
<br></br>
<input type="checkbox" name="QUESTION2" id="QUESTION2A3"/>
<label for="QUESTION2A3">Wednesday</label>
<br></br>
<input type="checkbox" name="QUESTION2" id="QUESTION2A4"/>
<label for="QUESTION2A4">Thursday</label>
<br></br>
<input type="checkbox" name="QUESTION2" id="QUESTION2A5"/>
<label for="QUESTION2A5">Friday</label>
<br></br>
<input type="checkbox" name="QUESTION2" id="QUESTION2A6"/>
<label for="QUESTION2A6">Saturday</label>
<br></br>
<input type="checkbox" name="QUESTION2" id="QUESTION2A7"/>
<label for="QUESTION2A7">Sunday</label>
<br></br>
</div>




Answer

Just a small alteration in your if condition should do the trick.

Please let me know if you need any assistance

if (this.checked && $('input[name='+$(this).prop('name')+']:checked').length > 3) {
   event.preventDefault();
   alert('You\'re not allowed to choose more than 3 boxes');
}