Sometimes, we want to change button text on click with JavaScript.
In this article, we’ll look at how to change button text on click with JavaScript.
How to change button text on click with JavaScript?
To change button text on click with JavaScript, we can add a click listener to the button.
For instance, we write
<input id="curtainInput" type="button" value="Open Curtain" />
to add a button input.
Then we write
document.getElementById("curtainInput").addEventListener(
"click",
(event) => {
if (event.target.value === "Open Curtain") {
event.target.value = "Close Curtain";
} else {
event.target.value = "Open Curtain";
}
},
false
);
to select the button with getElementById
.
Then we add a click listener to it with addEventListener
.
In it, we check if the value
attribute is 'Open Curtain'
.
If it is, we set it to 'Close Curtain'
.
Otherwise, we set it to 'Open Curtain'
.
Conclusion
To change button text on click with JavaScript, we can add a click listener to the button.