How to prevent unchecking all checkboxes using jquery?
Asked Answered
S

3

6

I have custom checkboxes:

<p>
    <input class="preventUncheck" id="toggle-on1" type="checkbox">
    <label for="toggle-on1">Selling</label>
</p>
<p>
    <input class="preventUncheck" id="toggle-on2" type="checkbox">           
    <label for="toggle-on2">Rent</label> 
</p>
$(function() {
    //prevent to uncheck all checkboxes
    $('.preventUncheck').on('change', function() {
        $('.preventUncheck').length == 0
        && !this.checked
        && $(this).prop('checked', true);
    });
});

I want to prevent unchecking all checkbox, that means alway one checkbox should be checked and if user try to unchecking it, javascript prevent to do it.

How can i do this work?

Sarong answered 2/2, 2017 at 11:26 Comment(2)
Your code is by default both are checked, and if you uncheck it, it should check again or not ?Tumbrel
In short, what you want to be more preciseTumbrel
T
7

You should check if length of checked checkbox is equal to 0 then prevent to unchecking it.

$('.preventUncheck').on('change', function(e) {
    if ($('.preventUncheck:checked').length == 0 && !this.checked)
    	this.checked = true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  <input type="checkbox" class="preventUncheck" id="toggle-on1">
  <label for="toggle-on1">Selling</label>
</p>
<p>
  <input type="checkbox" class="preventUncheck" id="toggle-on2">
  <label for="toggle-on2">Rent</label> 
</p>
Tranquilizer answered 2/2, 2017 at 11:33 Comment(1)
yeah ..thats it :) tnxSarong
W
0

Add attr "disabled" to the checkbox?

Watters answered 2/2, 2017 at 11:29 Comment(1)
@Sarong And what is your desired functionallity then?Watters
Z
0

You could also prevent unchecking of the last checked checkbox by disabling it as long as it is the sole checked one.

$('#demo').on('change', '.preventUncheck', function () {
    var $checkedEls = $('#demo .preventUncheck:checked');
    $checkedEls.prop('disabled', $checkedEls.length === 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="demo">
<p>
  <input type="checkbox" class="preventUncheck" id="toggle-on1" checked>
  <label for="toggle-on1">Sell</label>
</p>
<p>
  <input type="checkbox" class="preventUncheck" id="toggle-on2">
  <label for="toggle-on2">Rent</label> 
</p>
<p>
  <input type="checkbox" class="preventUncheck" id="toggle-on3" checked>
  <label for="toggle-on3">Lease</label> 
</p>
<p>
  <input type="checkbox" class="preventUncheck" id="toggle-on4">
  <label for="toggle-on4">Lend</label> 
</p>
</div>

(While at it, I also changed it so that only a single event handler is registered.)

Zworykin answered 2/9, 2022 at 9:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.