0

I have a GUI calcualtor, and I want to disable the digit buttons when the equal button is pressed.

Here is the HTML for the button which contains the digit 1:

<td>
  <button type="button" name="digit" value="1" value2 = "disabled">
    1
  </button>
</td>

This is the HTML for the equals button:

<button type="button" name="equals" value="=">
  =
</button>

Here is my JavaScript code attempting to disable it...

document.getElementsByName("equals")[0].addEventListener("click", function(){
  document.getElementsByName("digit").disabled = true;
});

Why is this not working? The event listener should disable it.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
EaEaEa
  • 21
  • 1
  • 3
  • There are different way you can do it. This is one way: `` `` – SeekLoad Jul 11 '17 at 16:36
  • And here is another way: `` `` – SeekLoad Jul 11 '17 at 16:38
  • Sorry I posted the answer as a comment, but somebody misunderstood your question and marked it as a duplicate, but I see no duplicate in your question. What I understood is that you simply want to disable one button, by the use of another. – SeekLoad Jul 11 '17 at 16:40
  • Personally I think this solution is the best since with this one you can add more then one button at the same time to be disabled from just one button click: `` `` – SeekLoad Jul 11 '17 at 16:53

1 Answers1

0

document.getElementsByName() returns a NodeList collection of elements.

Instead of document.getElementsByName("digit"), you're looking for document.getElementsByName("digit")[0] in order to access the first element in that collection.

document.getElementsByName("equals")[0].addEventListener("click", function(){
  document.getElementsByName("digit")[0].disabled = true;
});
<td>
  <button type="button" name="digit" value="1" value2="disabled">
    1
  </button>
</td>

<button type="button" name="equals" value="=">
  =
</button>

Hope this helps! :)

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71