0

How do I show an alert with Javascript if there are more than 4 checked checkboxes?

I have written the following code however it doesn't work.

var select1 = select = document.getElementById('edit-checkbox');

select1.onchange = function() {
if ($('#edit-checkbox').length > 4) {
 alert("Please dont choose more than 4 answers for this question!");
}

<div id="edit-checkbox">
    <input type="checkbox" name="rGroup" value="1" id="r1" checked="checked" />
    <label class="whatever" for="r1"></label>
    <input type="checkbox" name="rGroup" value="2" id="r2" />
    <label class="whatever" for="r2"></label>
    <input type="checkbox" name="rGroup" value="3" id="r3" />
    <label class="whatever" for="r3"></label>
</div>

2- Question: is it possible to disable the rest of the checkboxes dynamically, so that there is no need to show the alert?

allstar
  • 29
  • 1
  • 6

1 Answers1

0

Get checked count by $('#edit-checkbox input:checkbox:checked').length. Check below snippet for reference.

var select1 = select = document.getElementById('edit-checkbox');

select1.onchange = function() {
  if ($('#edit-checkbox input:checkbox:checked').length > 4) {
    alert("Please dont choose more than 4 answers for this question!");
    $('#edit-checkbox input:checkbox').removeAttr('checked');
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="edit-checkbox">
  <input type="checkbox" name="rGroup" value="1" id="r1" checked="checked" />
  <label class="whatever" for="r1"></label>
  <input type="checkbox" name="rGroup" value="2" id="r2" />
  <label class="whatever" for="r2"></label>
  <input type="checkbox" name="rGroup" value="3" id="r3" />
  <label class="whatever" for="r3"></label>
  <input type="checkbox" name="rGroup" value="4" id="r4" />
  <label class="whatever" for="r4"></label>
  <input type="checkbox" name="rGroup" value="5" id="r5" />
  <label class="whatever" for="r5"></label>
</div>

Updated: for second question, you can use slice() as below snippet.

$('#edit-checkbox input:checkbox').slice(4).attr('disabled', 'disabled');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="edit-checkbox">
  <input type="checkbox" name="rGroup" value="1" id="r1" checked="checked" />
  <label class="whatever" for="r1"></label>
  <input type="checkbox" name="rGroup" value="2" id="r2" />
  <label class="whatever" for="r2"></label>
  <input type="checkbox" name="rGroup" value="3" id="r3" />
  <label class="whatever" for="r3"></label>
  <input type="checkbox" name="rGroup" value="4" id="r4" />
  <label class="whatever" for="r4"></label>
  <input type="checkbox" name="rGroup" value="5" id="r5" />
  <label class="whatever" for="r5"></label>
  <input type="checkbox" name="rGroup" value="6" id="r6" />
  <label class="whatever" for="r6"></label>
</div>
RaJesh RiJo
  • 4,302
  • 4
  • 25
  • 46