Open In App

How to call a function when content of a div changes using jQuery ?

Improve
Improve
Like Article
Like
Save
Share
Report

The task is to call a function when the content of a div is changed. You can achieve this task by using the in-built method known as .change(). In simple words whenever the field is been changed we call a function that will throw a pop-up.

.change(): This method will only trigger when some change occurs in the element or field. It accepts an optional function as an argument that will perform some kind of work.

Syntax:

$(selector).change(function())

selector: It will select an element on which we have to perform this task.

function(): It is an optional argument that will specify the function to run when the change event occurs for the selected elements.

Approach 1: In this approach, we are going to implement its execution without taking any parameter such as function.

  • First, create an input box with some value and onChange attribute.
  • Create a button and map it to the script where you have written the change method without any argument.

Explanation: When you click a button trigger change event of the input field occurs and pop-up window will appear and display whatever present in the input field.

Example 1: 

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
      
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("input").change();
            });
        });
    </script>
</head>
  
<body>
    <p>
     <h1>
        Press enter to see the pop-up. 
        which says whatever written in the 
        input field 
     </h1>
    </p>
  
  
    <p>Enter anything you wish to: 
        <input value="GeeksForGeeks" 
        onchange="alert(this.value)" 
        type="text"></p>
    <button>
        Trigger change event for input field
    </button>
</body>
  
</html>


Output:

Before click:

After click:

Approach 2: In this approach, we are going to implement its execution with the help of function as an argument in the change method.

  • Make an input field of text type.
  • Map input element to the change() method and write some text to show on function call.

Explanation: When you enter something in the input field and press enter then the change event will run and executes the function and show the message that is written in the function.

Example 2:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
  
    <script>
        $(document).ready(function(){
            $("input").change(function(){
                alert("Welcome geek you have changed something.");
            });
        });
    </script>
</head>
  
<body>
    <input type="text">
    <p><h1>
        Enter something and press enter to see the effect.
    <h1></p>
</body>
  
</html>


Output:



Last Updated : 24 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads