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

i have a function that currently working on .keypress event when the user right something in the textbox it do some code, but i want the same event to be triggered also when the user clear the textbox .change doesn’t help since it fires after the user change the focus to something else

Thanks

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.

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 ...
});

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) {

    }
});

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

Inside your .keypress or .keyup function, check to see if the value of the input is empty. For example:

$("#some-input").keyup(function(){
 if($(this).val() == "") {
  // input is cleared
 }
});

<input type="text" id="some-input" />


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Pass new server data to react.js components

Similar Posts