Open In App

jQuery change() Method

Last Updated : 20 Sep, 2024
Suggest changes
Share
Like Article
Like
Report

The jQuery change() method is used to detect changes in the value of form elements like <input>, <select>, or <textarea>. It triggers a specified function when a user modifies the input or selects a different option.

Syntax

$(selector).change(function)

Parameters : It accepts an optional parameter "function". 

Example 1: In this example we demonstrates the change() method. When the button is clicked, the input field triggers the change() event, displaying an alert with the input's updated value.

HTML
<!DOCTYPE html> <html> <head> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">  </script> <!--Demo of change method without passing function--> <script>  $(document).ready(function () {  $("button").click(function () {  $("input").change();  });  });  </script> </head> <body> <p>Click the button to see the changed value !!!</p> <!--click on this button and see the change --> <button>Click Me!</button> <p>Enter value: <input value="GeeksforGeeks" onchange="alert(this.value)" type="text"> </p> </body> </html> 

Output: 

Example 2: In this example we applies the change() method to an input field. When the field value is modified and focus is lost, the input's background color changes to light green (#7FFF00).

HTML
<!DOCTYPE html> <html> <head> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">  </script> <!--Here function is passed to the change method--> <script>  $(document).ready(function () {  $(".field").change(function () {  $(this).css("background-color", "#7FFF00");  });  });  </script> <style>  .field {  padding: 5px;  }  </style> </head> <body> <!--write something and click outside --> Enter Value: <input class="field" type="text"> <p> Write something in the input field, and then press enter or click outside the field. </p> </body> </html> 

Output: 


Explore