How to avoid uncheck last checkbox...

Let say, You need to have a group of checkboxes and at least one have to be checked.
How can You do it?
First we need a group, then we can add fake html tag attribute called group. Then we need JavaScript function which handles checkbox click. It takes two arguments: event rising element and group to which it belongs to. This function looks for every input tag on document, but only when checkbox is unchecked (to rescue performance little bit). Then it tries to find every checkbox in group we sent to it. If there is not any checkbox checked left in the grop, it sets checked clicked checkbox again... easy? :D

function avoidUncheckLast(chk, group){
var theRestChecked = false;
if (chk.checked == false) {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].getAttribute("type") == "checkbox" &&
inputs[i].getAttribute("group") == group) {
if (chk!=inputs[i])
theRestChecked |= inputs[i].checked;
if (!theRestChecked) chk.checked=true;


<input type="checkbox" group="group1" onclick="avoidUncheckLast(this, 'group1');"/>


Newer Post Older Post Home