View video tutorial

HTML onchange Attribute

HTML

The onchange attribute is an event handler that defines a script to run when the value of a form element changes.

Definition and Usage


➔ In the case of text inputs (input type="text", textarea), the event is only fired when the user changes the value and the element loses focus.

➔ In the case of menus, checkboxes, and radio buttons, the event is fired as soon as the selected or checked state changes.

➔ oninput is triggered as soon as the value changes, whereas onchange waits for the element to lose focus.

Syntax
//In HTML    
<input type="text" onchange="myFunction()">

// In Javascript object 
object.onchange = (event) => { };

// Using EventListener 
object.addEventListener("change", (event) => { });

Applies to

This attribute can be used on the following element.

Attribute Element
onchange All visible elements

Example
<!DOCTYPE html>
<html>
<head>
    <title>HTML onchange Attribute Example</title>
    <meta charset="utf-8" />
    <style>
         input[type="text"]{
            width: 230px;
            height: 30px;
            background-color: #efffff;
            font-size: 14pt;
            color: #000;
            border-radius: 5px;
            margin: 5px;
        }

        input[type="text"]:hover{
            background-color: #fff;
        }
    </style>
</head>
<body>
    <h2>HTML onchange Attribute Example</h2>
    <p>Change the text in the input field, click outside the field to fire the onchange event.</p>
    <form action="/sample.jsp" method="POST">
        Name: <input type="text" name="name" onchange="myHandler(this.value)"><br>
    </form>
    <script>
        function myHandler(v) {
            alert("The value has changed to: " + v);
        }
    </script>
</body>
</html>

Click on the "copy" button and try this example in your project.