onchange
The onchange event is triggered when the value of an HTML element is altered.
onchange event
The onchange event occurs when the value of an input element is modified and loses focus. This event is often used with form elements such as <input>
, <select>
, and <textarea>
. To use it, add the attribute to the desired element and specify the script that should execute when the event is triggered.
Syntax
In HTML
index.html
<element onchange="myScript">
In JS
script.js
object.onchange = function(){myScript};
addEventListener()
function is used. In JavaScript, the
script.js
object.addEventListener("change", myScript);
Example
::event-onchange
::
index.html
<!DOCTYPE html>
<html>
<body>
<p>Select a new car from the list.</p>
<select id="mySelect" onchange="myFunction()">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
<option value="Volvo">Volvo</option>
</select>
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>
</body>
</html>
Values
onchange
event is comparable to the oninput
event. The key difference is that the oninput
event is triggered as soon as the value of an element changes, whereas the onchange
event occurs after the element loses focus.Conclusion
The onchange
event is an essential tool for capturing changes in input values, especially within form elements such as <input>
, <select>
, and <textarea>
. By using this event, developers can trigger specific actions, such as validation or updating content, once a user modifies and moves away from an input element.