lundi 12 juin 2023

What is the difference in the operation of JS functions with checkboxes in HTML?

I'm trying to figure out how to work with a checkbox using JS.

Why does setAttribute("disabled", "") work only when I click checkbox class`s "ch2"?

HTML:

<input type="checkbox" class="ch1" name="ch1" onclick="fn_for_two_chb()">
<label for="ch1">ch1</label>
<input type="checkbox" class="ch2" name="ch2" onclick="fn_for_two_chb()">
<label for="ch2">ch2</label>

JS:

const chb_1 = document.querySelector('.ch1')
const chb_2 = document.querySelector('.ch2')

function fn_for_two_chb() {
    if (chb_1.checked == true) {
            chb_2.setAttribute("disabled", "");
    } else {
            chb_1.removeAttribute("disabled", "");
            chb_2.removeAttribute("disabled", "");
    }

    if (chb_2.checked == true) {
            chb_1.setAttribute("disabled", "");
    } else{
            chb_1.removeAttribute("disabled", "");
            chb_2.removeAttribute("disabled", "");
    }
  }

But when I split this into two functions and assign them to different checkboxes in HTML, it works.

HTML:

<input type="checkbox" class="ch1" name="ch1" onclick="fn_chb_1()">
<label for="ch1">ch1</label>
<input type="checkbox" class="ch2" name="ch2" onclick="fn_chb_2()">
<label for="ch2">ch2</label>

JS:

function fn_chb_1() {

    if (chb_1.checked == true) {
            chb_2.setAttribute("disabled", "");
    } else {
            chb_1.removeAttribute("disabled", "");
            chb_2.removeAttribute("disabled", "");
    }
  }

function fn_chb_2() {

    if (chb_2.checked == true) {
            chb_1.setAttribute("disabled", "");
    } else {
            chb_1.removeAttribute("disabled", "");
            chb_2.removeAttribute("disabled", "");
    }
  }



Aucun commentaire:

Enregistrer un commentaire