Detect if textarea content has changed with JavaScript/jQuery
This post will discuss how to detect if textarea content has changed in JavaScript and jQuery.
1. Using jQuery
With jQuery, you can bind the input JavaScript event to the textarea, which fires when the value of a <textarea>
element changes. The input
event fires on standard input, on paste, auto-fill, etc.
The following example throws an alert whenever the <textarea>
content is changed.
JS
1 2 3 |
$(document).ready(function() { $('#story').on('input', (event) => alert('Changed!')); }); |
HTML
1 2 3 |
<textarea id="story" name="story" rows="5" cols="33"> Once upon a time… </textarea> |
Note that the change
event fires once only when the value is committed (i.e., when the <textarea>
loses focus), unlike the input
event, which fires every time the value is changed. You can use it depending upon your use case.
JS
1 2 3 |
$("#story").change(function() { alert('Textarea is changed'); }); |
HTML
1 2 3 |
<textarea id="story" name="story" rows="5" cols="33"> Once upon a time… </textarea> |
2. Using JavaScript
In pure JavaScript, you can bind the input JavaScript event to the textarea with the addEventListener() method. Here’s a working example in JavaScript.
JS
1 2 |
document.getElementById("story") .addEventListener("input", (event) => alert("Changed!")); |
HTML
1 2 3 |
<textarea id="story" name="story" rows="5" cols="33"> Once upon a time… </textarea> |
Alternatively, you can use the oninput
property to specify an event handler to receive input events. In the following example, the oninput
event handler is fired whenever any change is the textarea.
HTML
1 2 3 |
<textarea id="story" name="story" rows="5" cols="33" oninput="display();"> Once upon a time… </textarea> |
JS
1 |
var display = () => alert("Changed!"); |
That’s all about detecting if textarea content has changed in JavaScript and jQuery.
Automatically resize textarea height to fit text with JavaScript/jQuery
Detect clicks outside an HTML element with JavaScript/jQuery
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)