[javascript] How can I bind to the change event of a textarea in jQuery?

I want to capture if any changes happened to <textarea>. Like typing any characters (deleting,backspace) or mouse click and paste or cut. Is there a jQuery event that can trigger for all those events?

I tried change event, but it triggers the callback only after tabbing out from the component.

Use: I want to enable a button if a <textarea> contains any text.

This question is related to javascript jquery jquery-ui

The answer is


After some experimentation I came up with this implementation:

$('.detect-change')
    .on('change cut paste', function(e) {
        console.log("Change detected.");
        contentModified = true;
    })
    .keypress(function(e) {
        if (e.which !== 0 && e.altKey == false && e.ctrlKey == false && e.metaKey == false) {
            console.log("Change detected.");
            contentModified = true;
        }
    });

Handles changes to any kind of input and select as well as textareas ignoring arrow keys and things like ctrl, cmd, function keys, etc.

Note: I've only tried this in FF since it's for a FF add-on.


Try to do it with focusout

$("textarea").focusout(function() {
   alert('textarea focusout');
});

.delegate is the only one that is working to me with jQuery JavaScript Library v2.1.1

 $(document).delegate('#textareaID','change', function() {
          console.log("change!");
    });

Use an input event.

var button = $("#buttonId");
$("#textareaID").on('input',function(e){
  if(e.target.value === ''){
    // Textarea has no value
    button.hide();
  } else {
    // Textarea has a value
    button.show();
  }
});

Here's another (modern) but slightly different version than the ones mentioned before. Tested with IE9:

$('#textareaID').on('input change keyup', function () {
  if (this.value.length) {
    // textarea has content
  } else {
    // textarea is empty
  }
});

For outdated browsers you might also add selectionchange and propertychange (as mentioned in other answers). But selectionchange didn't work for me in IE9. That's why I added keyup.


Try this

 $('textarea').trigger('change');
 $("textarea").bind('cut paste', function(e) { });

try this ...

$("#txtAreaID").bind("keyup", function(event, ui) {                          

              // Write your code here       
 });

bind is deprecated. Use on:

$("#textarea").on('change keyup paste', function() {
    // your code here
});

Note: The code above will fire multiple times, once for each matching trigger-type. To handle that, do something like this:

var oldVal = "";
$("#textarea").on("change keyup paste", function() {
    var currentVal = $(this).val();
    if(currentVal == oldVal) {
        return; //check to prevent multiple simultaneous triggers
    }

    oldVal = currentVal;
    //action to be performed on textarea changed
    alert("changed!");
});

jsFiddle Demo


This question needed a more up-to-date answer, with sources. This is what actually works (though you don't have to take my word for it):

// Storing this jQuery object outside of the event callback 
// prevents jQuery from having to search the DOM for it again
// every time an event is fired.
var $myButton = $("#buttonID")

// input           :: for all modern browsers [1]
// selectionchange :: for IE9 [2]
// propertychange  :: for <IE9 [3]
$('#textareaID').on('input selectionchange propertychange', function() {

  // This is the correct way to enable/disabled a button in jQuery [4]
  $myButton.prop('disabled', this.value.length === 0)

}

1: https://developer.mozilla.org/en-US/docs/Web/Events/input#Browser_compatibility
2: oninput in IE9 doesn't fire when we hit BACKSPACE / DEL / do CUT
3: https://msdn.microsoft.com/en-us/library/ms536956(v=vs.85).aspx
4: http://api.jquery.com/prop/#prop-propertyName-function

BUT, for a more global solution that you can use throughout your project, I recommend using the textchange jQuery plugin to gain a new, cross-browser compatible textchange event. It was developed by the same person who implemented the equivalent onChange event for Facebook's ReactJS, which they use for nearly their entire website. And I think it's safe to say, if it's a robust enough solution for Facebook, it's probably robust enough for you. :-)

UPDATE: If you happen to need features like drag and drop support in Internet Explorer, you may instead want to check out pandell's more recently updated fork of jquery-splendid-textchange.


2018, without JQUERY

The question is with JQuery, it's just FYI.

JS

let textareaID = document.getElementById('textareaID');
let yourBtnID = document.getElementById('yourBtnID');
textareaID.addEventListener('input', function() {
    yourBtnID.style.display = 'none';
    if (textareaID.value.length) {
        yourBtnID.style.display = 'inline-block';
    }
});

HTML

<textarea id="textareaID"></textarea>
<button id="yourBtnID" style="display: none;">click me</div>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-ui

How to auto adjust the div size for all mobile / tablet display formats? jQuery not working with IE 11 JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined Best Practice to Organize Javascript Library & CSS Folder Structure Change table header color using bootstrap How to get HTML 5 input type="date" working in Firefox and/or IE 10 Form Submit jQuery does not work Disable future dates after today in Jquery Ui Datepicker How to Set Active Tab in jQuery Ui How to use source: function()... and AJAX in JQuery UI autocomplete