EN
JavaScript - oninput vs onchange
0 points
In this article, we would like to show you oninput
vs onchange
events comparison in JavaScript.
oninput
- executes JavaScript code when the value of the HTML element is changed. This can be done by e.g typing something manually in textarea
or by pasting some text to the input.
onchange
- executes JavaScript code when the state or the contents of an element have changed. This can be done by e.g checking/unchecking radio input (or checkbox), losing focus of the textarea
, etc.
In this section, we present oninput
and onchange
events comparison, check the runnable example below to see the differences.
Notice that oninput
event triggers when you input the text and onchange
event triggers when the input
loses the focus.
Runnable example:
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script>
5
6
function myFunction(input) {
7
console.clear();
8
console.log(`Current ${input.id} value: ` + input.value);
9
}
10
11
</script>
12
</head>
13
<body>
14
<h2>oninput</h2>
15
<span>Type something or paste text to trigger oninput event:</span>
16
<input type="text" id="input1" oninput="myFunction(this)">
17
<h2>onchange</h2>
18
<span>Type something and lose focus to trigger onchange event:</span>
19
<input type="text" id="input2" onchange="myFunction(this)">
20
</body>
21
</html>