Account
Categories

JavaScript onchange Event: Input Change


Definition:

The onchange event is used on input fields to run a function when the user changes the value.

When you use the onchange event on a form input, it runs a function whenever the user changes the data.

If the input is wrong, you can show a message.

If the input is correct, you can update the value or do other tasks.

Now you will clearly understand with the help of the flowchart.

Start
   |
   v
Create Form Input (Name, Email, Contact, Message)
   |
   v
Add onchange Function --> [This function runs when the user changes input]
   |
   v
User types or changes data in the input
   |
   v
onchange Function runs
   |
   |-- Is Name valid? --No--> Show alert/message
   |-- Yes --> Is Email valid? ...
   ...
   |
All inputs valid --> Continue / Update / Do task.
   |
   v
End
  

Example:

<!DOCTYPE html>
<html>
<head>
  <title>Onchange Event Example</title>
  <script>
    // This function checks the input when it changes
    function checkName() {
      let name = document.getElementById("name").value;
      // If Name is empty, show alert
      if(name === "") {
        alert("Name cannot be empty!");
      } else {
        // If Name is entered, show success message
        console.log("Name is entered correctly: " + name);
      }
    }

    function checkEmail() {
      let email = document.getElementById("email").value;
      // If Email is empty or does not have @, show alert
      if(email === "" || !email.includes("@")) {
        alert("Please enter a valid email!");
      } else {
        console.log("Email is correct: " + email);
      }
    }
  </script>
</head>
<body>
  <h2>Form with Onchange Event</h2>
  <form>
    <label for="name">Name:</label><br>
    <input type="text" id="name" name="name" onchange="checkName()"><br><br>

    <label for="email">Email:</label><br>
    <input type="text" id="email" name="email" onchange="checkEmail()"><br><br>

    <label for="message">Message:</label><br>
    <textarea id="message" name="message"></textarea><br><br>

    <button type="submit">Submit</button>
  </form>
</body>
</html>