Home >Web Front-end >JS Tutorial >Why Isn't My Calculator's Clear Button Working?
Why onClick Event Is Not Working for the Clear Function?
In an attempt to create a simple calculator, you've encountered an issue where the clear button's onClick attribute fails to clear the text field. Despite the code, the error persists. Let's explore this problem.
The onClick attribute assigns an inline event handler, which is deprecated due to its implementation using the with statement. Internally, it executes as document.clear() instead of the intended clear() function.
Solution:
However, for better code practices, it's recommended to bind event handlers using addEventListener instead of inline attributes:
document.getElementById("clearButton").addEventListener("click", () => { clear(); });
The above is the detailed content of Why Isn't My Calculator's Clear Button Working?. For more information, please follow other related articles on the PHP Chinese website!