How to use an HTML button to call a JavaScript function?

Spread the love

Sometimes, we want to use an HTML button to call a JavaScript function.

In this article, we’ll look at how to use an HTML button to call a JavaScript function.

How to use an HTML button to call a JavaScript function?

To use an HTML button to call a JavaScript function, we set the button’s onclick property toi the function we want to call when we click it.

For instance, we write

<input id="clickMe" type="button" value="clickme" />

to add a button.

Then we write

document.getElementById("clickMe").onclick = () => {
  alert("hello!");
};

to select the button with getElementById.

And we set its onclick property to a function that calls alert when we click the button.

Conclusion

To use an HTML button to call a JavaScript function, we set the button’s onclick property toi the function we want to call when we click it.

Leave a Reply

Your email address will not be published.