JavaScript onchange with 2 examples

The onchange event

The HTML onchange event occurs when an element’s value is changed. For example when you change/select a value in dropdown or enter or remove text in a textbox, the onchange event occurs.

You can attach JavaScript to perform some actions as the onchange event occurs. This tutorial will show you examples of using the onchange event with different HTML elements.

This is how you can attach or trigger javascript in onchage event of HTML’s select element.

<select onchange=”showalert()”>

Now, let us look at a few example of using javascript and onchange event.

Select with onchange example

Following is an HTML select example as the onchange event occurs. The dropdown is filled with three options. When you select or change an option in the dropdown, the onchange event will occur. We attached a JavaScript function that will trigger and it will show the selected value in an alert. See example by clicking the link below:

Experience this example online


As you can see, upon selecting a new option the onchange event occurred in the select element that executed the “showalert” JavaScript function. The function threw an alert with the selected value.

onchange example with input type = text

Following is an onchange with javascript example where we are using a textbox (Form input element). As you enter some text in the textbox and leave it, by using the tab key of keyboard or clicking the mouse at some other part of the web page, the onchange event will occur that will show an alert with the textbox value.

Experience this example online


You can see the alert showed text in the textbox, by using JavaScript function as the onchange event occurred.

Also see JavaScript onclick | JavaScript onsubmit 

Was this article helpful?

Related Articles

Leave A Comment?