The onclick event in JavaScript

In your web pages, the HTML onclick event occurs when an element is clicked (single click). For example, clicking a button, a link or other HTML element. In order to perform some action, you can attach JavaScript code to the onlick event.

For example showing a warning message in an alert as a button is clicked. Similarly, after filling a form, a user clicks the submit button where you can show any error occurred in filling the form before submitting to the server, by using the onclick event.

An example of onclick

Following is a way to use JavaScript onclick to an HTML element (button’s onclick):

<button onclick=”JSfunction()”>

The above line tells to execute JavaScript code as the onclick event occurs in the button element.

Now let us look at the working online examples of using the onclick event.

A button onclick example

Following is an HTML button onclick example. As you click the button, the JavaScript function will be called that will show an alert. See the example by clicking the link or image:

Experience this example online

As you can see, when you click on the button, the button’s onclick event will call JavaScript function “showalert” that will show an alert with a message: “Button onclick event occurred”.

The onclick with href (link) example

Following is an example of JavaScript onlick with the href example. As you click on the link, the onclick event occurs. We will attach a JavaScript function that will show an alert.

Experience this example online

The <a href> onclick triggering JavaScript function that throws an alert. In the link tag <a>, after the href attribute, the onclick is placed with a JavaScript function.

onclick and JavaScript example with a div element

Not only the onclick event works for button or link but you can also use it in div, headings, and other HTML elements. Following is an onclick example with a div element. As you click on the div element it will show an alert.

Experience this example online

onclick example with radio buttons

The HTML onclick event also occurs when a radio button is clicked. You can get its value and use in JavaScript code.

In the following example, as you click on a choice given in radio buttons, the function will be called and an alert will be shown with the respective value.

Experience this example online

You can see, the selected marital status option is shown by using JavaScript onclick.