Categories
JavaScript Answers

How to change button text on click with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *