Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 831
trrrrrrm Avatar asked Dec 09 '10 21:12

trrrrrrm


4 Answers

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.

like image 107
Jonathon Bolster Avatar answered Sep 25 '22 00:09

Jonathon Bolster


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 ...
});
like image 29
Gonfi den Tschal Avatar answered Sep 22 '22 00:09

Gonfi den Tschal


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

    }
});
like image 3
Rose Avatar answered Sep 24 '22 00:09

Rose


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

like image 2
NJENGAH Avatar answered Sep 21 '22 00:09

NJENGAH