jQuery change() Method triggers the change event, when the value of an html element has been changed. The elements covered by this method are <input>, <textarea> and <select>, if the value of any of these elements is changed then the change() method triggers change event. jQuery change() Method attaches these html elements (<input>, <textarea> and <select>) to the event handler function and when the change event is triggered, the event handler function executes.
jQuery change() Method Syntax
$(selector).change(function(){ //code that executes when the change event is occurred. });
Here $(selector) can be $(“input”), $(“textarea”) or $(“select”).
jQuery change() Example
In the following example, we have a textarea and we have attached the “textarea” to event handler function using change() method, which means when the value of the textarea changes, the event handler function executes.
To demonstrate the change event, we have typed a sentence in “textarea” and then clicked outside of the “textarea”, this triggered the change event and the event handler function executes, in the event handler function we are displaying an alert message which you see in the output screenshots.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("textarea").change(function(){ alert("The text in textarea has been changed."); }); }); </script> </head> <body> <h2>jQuery change event example on Beginnersbook.com</h2> <textarea type="text"></textarea> <p>Write something in the textarea and then click outside of the textarea box. You will see an alert message that the value of the textarea has been changed.</p> </body> </html>
Output:
Before the value of textarea is changed:
When the page is initially loaded and we have performed no action on the page.
After the value of textarea is changed:
We have typed a message in the textarea and then clicked outside the textarea, this action changed the value of textarea thus triggered the change event and we got an alert message on the screen, which we have set in the change event handler function.
Leave a Reply