1

I'm trying to disables inputs with the name "q1", however It just doesn't disable them.

The line of code is just

if (time < 0){
    document.getElementById("lose").innerHTML = "O tempo acabou!";
    document.getElementById("nextQuestion").style.display = "block"
    document.getElementsByName("q1").disabled = true
}

The other document.getElementById work.

The html is

<br><br><input type="submit" name="q1" value="arroz">
            <input type="submit" name="q1" value="massa"><br><br>
            <input type="submit" name="q1" value="Apanhado em flagrante">
            <input type="submit" name="q1" value="batata de tremoços"><br><br><br>`
  • 4
    `getElementsByName` returns collection. Perhaps you meant `document.getElementsByName("q1")[0].disabled`? – danronmoon Feb 26 '19 at 21:07
  • document.getElementsByName("q1") returns list of elements with name q1, so you should loop and disable – Naga Sai A Feb 26 '19 at 21:07
  • You have lot's of inputs with the name 'q1', so you should probably make them each unique. Or get the proper index – dwib Feb 26 '19 at 21:08
  • 1
    Oh, I didn't know it returned a list, I was expecting it to just disable them all. Thanks! –  Feb 26 '19 at 21:09

1 Answers1

1

document.getElementsByName returns a NodeList, which is sort of like an array. You need to loop through it and disable each element.

The NodeList would contain all the elements that have the name q1, and the code below (specifically the .forEach() loop) will disable each element with the name of q1

time = -1;

if (time < 0){
    document.getElementById("lose").innerHTML = "O tempo acabou!";
    document.getElementById("nextQuestion").style.display = "block"
    document.getElementsByName("q1").forEach(e => {
      e.disabled = true;
    });
}
<br><br><input type="submit" name="q1" value="arroz">
<input type="submit" name="q1" value="massa"><br><br>
<input type="submit" name="q1" value="Apanhado em flagrante">
<input type="submit" name="q1" value="batata de tremoços"><br><br><br>
<div id="lose"></div>
<div id="nextQuestion"></div>
Aniket G
  • 3,471
  • 1
  • 13
  • 39
  • 2
    The e in the foreach loop is each element of q1 right? –  Feb 26 '19 at 21:13
  • 2
    @DuarteArribas yes. In foreach loops, we usually use `element` to signify that it's the element. I've started using `e` which is easier to type, but means the same thing – Aniket G Feb 26 '19 at 22:30