Jquery : how to trigger an event when the user clear a textbox

You can check the value of the input field inside the on input' function() and combine it with an if/else statement and it will work very well as in the code below :

$( "#myinputid" ).on('input', function() {

         if($(this).val() != "") {

           //Do action here like in this example am hiding the previous table row

                   $(this).closest("tr").prev("tr").hide(); //hides previous row

         }else{

             $(this).closest("tr").prev("tr").show(); //shows previous row
         }
    });

enter image description here


Another way that does this in a concise manner is listening for "input" event on textarea/input-type:text fields

/**
 * Listens on textarea input.
 * Considers: undo, cut, paste, backspc, keyboard input, etc
 */
$("#myContainer").on("input", "textarea", function() {
    if (!this.value) {

    }
});

The solution by Jonathon Bolster does not cover all cases. I adapted it to also cover modifications by cutting and pasting:

$("#inputname").on('change keyup copy paste cut', function() {
    //!this.value ...
});

see http://jsfiddle.net/gonfidentschal/XxLq2/

Unfortunately it's not possible to catch the cases where the field's value is set using javascript. If you set the value yourself it's not an issue because you know when you do it... but when you're using a library such as AngularJS that updates the view when the state changes then it can be a bit more work. Or you have to use a timer to check the value.

Also see the answer for Detecting input change in jQuery? which suggests the 'input' event understood by modern browsers. So just:

$("#inputname").on('input', function() {
    //!this.value ...
});

The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)

$("#inputname").keyup(function() {

    if (!this.value) {
        alert('The box is empty');
    }

});

jsFiddle

As Josh says, this gets fired for every character code that is pressed in the input. This is mostly just showing that you need to use the keyup event to trigger backspace, rather than the keypress event you are currently using.