0

Here I'm using firebase to display all driver info one by in one div. I have 6 div(i.e 6 object in driver reference) & each div has a checkbox with enabled/disabled option. I want operate checkbox in such way that if I click checkbox of 1st div it will change in only in 1st div,if I click checkbox of 2nd div it will change in only in 2nd div,& so on but the problem is when I clicked any checkbox only 1st checkbox is change... How can I overcome this...thanks in advance

<script>
function contactHtmlFromObject(Key, Driver){
  console.log(Key,Driver);
    if(Driver.Gender=='Male'){
            html +='<input type="checkbox" id="disablecheckbox" onclick="loaddisable(\''+Key+'\')"><span id="toggle">Enabled</span>';
        }
        else{
            html +='<input type="checkbox" id="disablecheckbox" onclick="loaddisable(\''+Key+'\')" checked><span id="toggle">Disabled</span>';
        }
}


function loaddisable(Key) {
    var toggle= document.getElementById("toggle");
    var dcb= document.getElementById("disablecheckbox");
    var Refdis = firebase.database().ref("Driver/"+Key);      
    Refdis.on("value", function(snapshot) {
    if (dcb.checked == true){
      toggle.innerHTML="Disabled";
        }
    else {
      toggle.innerHTML="Enabled";
  }
});
}
IHM365
  • 43
  • 1
  • 1
  • 8

1 Answers1

0

As the nice folks from the comments already suggested, your IDs aren't unique. That's the whole purpose of a ID, right ?! :)

So your JS functions look at the first element with the id, does what it supposed to do with it, and stops.

Instead of using id, I used a class as the selector and built two functions:

  1. One for enabling the checkbox
  2. One for disabling them.

I achieved that simply by looping over the elements that have that specific class name.

Check out the code snippet and see if it works for you ;)

function disable(obj){
    const elem = document.getElementsByClassName("checks");
    for(let i = 0; i < elem.length; i++){
        if(obj != elem[i]){
            elem[i].disabled = true;
        }
    }
}

function enable(obj){
    const elem = document.getElementsByClassName("checks");
    for(let i = 0; i < elem.length; i++){
        if(obj != elem[i]){
            elem[i].disabled = false;
        }
    }
}
Checkbox 1: <input type="checkbox" class="checks"> <br>
Checkbox 2: <input type="checkbox" class="checks"> <br>
Checkbox 3: <input type="checkbox" class="checks"> <br>
Checkbox 4: <input type="checkbox" class="checks"> <br>
Checkbox 5: <input type="checkbox" class="checks"> <br>

<button onclick="disable(this)">Disable All</button>
<button onclick="enable(this)">Enable All</button>
Dženis H.
  • 7,284
  • 3
  • 25
  • 44