Search code examples
javascriptdomids

Use multiple ID'S in DOM Javascript


the main idea is to try to disable multiple checkboxes using multiple ID'S for example using documentGetElementById

Each id belongs to a checkbox

function main(){
var a = document.getElementById("actual").value;
var b = document.getElementById("destination").value;

if (a == "Jamaica" && b == "Paris"){
document.getElementById("A", "B", "C", "D").disabled = true; // occupied seats
}
}


Solution

  • You have three options:

    1.) Multiple calls

    document.getElementById("A").disabled = true;
    document.getElementById("B").disabled = true;
    // and so on...
    

    2.) Loop over the IDs

    ["A", "B", "C", "D"].forEach(id => document.getElementById(id).disabled = true)
    

    3.) You find a selector that matches all of them and use document.querySelectorAll. IDs have to be unique, so that won't suffice, but let's say all checkboxes on the page need to be disabled:

    document.querySelectorAll("input[type='checkbox']").forEach(elem => elem.disabled = true);
    

    For this option, you can alternatively use other CSS selectors that would select the desired checkboxes, like a class name.