The onChange event handler in JavaScript is used to execute a function when the value of an input element changes. It is commonly used with form elements such as <input>, <select>, and <textarea>. The purpose of onChange is to capture user input and respond to it, allowing for dynamic updates to the user interface or validation of input data.
Here’s a simple example of how onChange can be used with an input field:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>onChange Example</title>
</head>
<body>
<input type="text" id="myInput" onChange="handleChange()">
<p id="output"></p>
<script>
function handleChange() {
const input = document.getElementById('myInput').value;
document.getElementById('output').innerText = `You entered: ${input}`;
}
</script>
</body>
</html>
In this example, when the user changes the text in the input field, the handleChange function is called, and it updates the paragraph with the entered value.
