hi there, could someone share ideas coz trying to learn DOM events, making calculator and have display which is <input type="text" id="answer">
. I am setting it to document.querySelector("#answer").value=“0”.
And have buttons with class=“number” and want to make keypress event for any button with class=“number” getting hit, would change input text into that number. How it should be done with addEventListener(keypress, function)?
Hi,
First of all, for the text element it should be document.getElementById(“answer”).value and not what you wrote. This is because you are picking that element by its id, not class. Queryselector is usually used to pick an element by class name. Also put the id without the # sign.
To add event listeners, the syntax is:
element.addEventListener(event, callback_function)
In this you will need to replace the element placeholder by the buttons. The buttons can be picked by their ids by using document.getElementById function and replaced in the element placeholder.
The event will be your keypress event. And the function will be the callback function defined inside the event listener, which would contain the code to show numbers on the screen when the user presses the keys.
Now for so many buttons to add event listeners to, instead of doing it one by one, try putting those in a loop or so and then adding their ids dynamically to the document.getElementById function within that loop. For that, you should use alphanumeric ids for the buttons such that those can be calculated dynamically in the JS loop too and put into the getElementById().
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.