Search code examples
javascriptcheckboxonclickpreventdefault

Javascript: Problems in firefox with checkbox + label + preventDefault


I have two hidden checkboxes, each linked to a label (each label's color reflects the linked checkbox's state -- css). I do that for styling reasons; using pure checkboxes would cause no problem, btw.

Now there is some logic behind:
1. Checkbox A can only be checked if checkbox B is checked; rejection is done by using a return statement in the onlick (~preventDefault)
2. Thus, if B is being unchecked, but A is checked, A will be unchecked automatically (and cannot be checked again, until B is checked again)
3. When checking B, A will be checked automatically (but it can be unchecked again manually as long as B remains checked)

It works quite fine, except for one thing:
1. Enter the page (A and B are unchecked by default)
2. Now click A: action will be rejected correctly because B is unchecked
3. Now click B: actually A should now get checked too, but instead 'disabled' is prompted and A remains unchecked -- WRONG

If you skip step 2, there will be no problem.

Using an actual event.preventDefault command doesn't change anything.

Seems to be working fine in Chrome.

<input type="checkbox" id="checkA" unchecked />
<label for="checkA" id="checkALabel" onclick="{
    const $ = x => document.getElementById(x);

    // Reject if user tries to check checkA although checkB is false
    if (!$('checkA').checked && !$('checkB').checked) {
        alert('rejected');
        return false;
    }
    return true;
}">[check a]</label>

<input type="checkbox" id="checkB" onchange="{
    const $ = x => document.getElementById(x);

    // If [checkB is true but checkA not checked] then check checkA
    // or if [checkB is false and checkA checked] then uncheck checkA
    if ($('checkA').checked ^ $('checkB').checked) {
        $('checkALabel').click();
        if (!$('checkA').checked) {
            alert('disabled')
        }
    }
}" unchecked />
<label for="checkB">[check b]</label>

https://jsfiddle.net/zncmgs4o/


Solution

  • If you replace $('checkALabel').click(); with $('checkA').click(); then it will work in Firefox too.

    Seems that Firefox prevents the programmatic .click call on the label from checking the associated checkbox.