Open In App

How to detect If textbox content has changed using JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

The task is to detect the changes in the textbox content with JavaScript. Whenever a user writes or types something in the input text box we have to detect that event by the use of some methods present in JavaScript.

There are some common approaches that are discussed below:

Approach 1: Using onchange event

We will use the onchange event in the input element and call a function to see the effect.

Example: In this example, we are using the above-explained approach.

html




<!DOCTYPE html>
<html>
 
<head>
  <title>
    Detect If Textbox content has
    changed using pure JavaScript
  </title>
</head>
 
<body style="text-align:center;">
  <h1 style="color:green;">
    GeeksforGeeks
  </h1>
  <p>
    Change the text of input text
    and click outside of it to see.
  </p>
  <input id="input"
         name="input"
         onchange="GFG_Fun()" />
  <br>
  <br>
  <script>
    function GFG_Fun() {
      alert('Changed');
    }
  </script>
</body>
</html>


Output:

Approach 2: Using onpropertychange event

There are few other events that can be used to detect the change in content of textbox. Use any or all of them onchange event, onpropertychange event, onkeyup event, onpaste event and oninput event in the input element and call a function to see the effect.

Example: In this example, we are implementing the above approach.

html




<!DOCTYPE html>
<html>
 
<head>
    <title>
        Detect If Textbox content has
        changed using pure JavaScript
    </title>
</head>
 
<body style="text-align:center;">
    <h1 style="color:green;">
    GeeksforGeeks
    </h1>
    <p>
    Change the text of input text and
    click outside of it to see.
    </p>
    <input id="input" name="input"
        onchange
        onpropertychange
        onkeyuponpaste oninput="GFG_Fun()" />
    <br>
    <br>
    <script>
        function GFG_Fun() {
            alert('Changed');
        }
    </script>
</body>
 
</html>


Output:

Approach 3: Using addEventListener() method

In javascript with the help of the addEventListener() method, we can attach the input javascript event to the textarea.

Example: In this example, we are using the above-explained approach.

HTML




<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    h1 {
      text-align: center;
    }
 
    .abc {
      display: flex;
      justify-content: center;
      text-align: center;
    }
  </style>
</head>
 
<body>
  <h1 style="color:green;">
    GeeksforGeeks
  </h1>
  <div class="abc">
    <input id="gfg">
  </div>
 
  <script>
    document.getElementById("gfg")
      .addEventListener("input", (event) => alert("Changed!"));
 
  </script>
</body>
</html>


Output:

Output

 



Last Updated : 20 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads