scireon
scireon

Reputation: 5

Temporary Disable Keyup event when text input is blank

I am a beginner in jquery but I've tried my best to do this, but unfortunately I missed something

How can I temporary disable keyup event when text input is blank and enable it again after I have typed something on it?

I cannot cannot catch backspace in keypress so I used keyup. Here is my code

$('#searchBox').keyup(function(e){
if(e.keyCode != '18' && e.keyCode != '91' && e.keyCode != '17' && e.keyCode != '16' && e.keyCode != '20' && e.keyCode != '27' && e.keyCode != '113' && e.keyCode != '115' && e.keyCode != '118' && e.keyCode != '119' && e.keyCode != '120' && e.keyCode != '122' && e.keyCode != '123' && e.keyCode != '44' && e.keyCode != '19' && e.keyCode != '45' && e.keyCode != '46' && e.keyCode != '36' && e.keyCode != '33' && e.keyCode != '34' && e.keyCode != '35' && e.keyCode != '39' && e.keyCode != '37' && e.keyCode != '38' && e.keyCode != '9'){
    if(e.keyCode == '8' && $(this).val()==""){
        //what will i put here
    }else if(e.keyCode == '8' && $(this).val()!=""){
        refreshWookmark($(this).val());
    }else{
        refreshWookmark($(this).val());
    }
}
});

Upvotes: 0

Views: 2044

Answers (4)

Tryadon
Tryadon

Reputation: 11

To disable keyup function or others functions try this

  if()
    {
    obj.keyup(function () {
    //code
    });
    }else{
    obj.unbind("keyup")
    }

Upvotes: 1

PlantTheIdea
PlantTheIdea

Reputation: 16369

Rather than disable it, just check that input exists and that the keyCode is what you consider valid:

$('#searchBox').on('keyup',function(e){
    var bad = ['18','91','17','16','20','27','113','115','118','119','120','122','123','44','19','45','46','36','33','34','35','39','37','38','9'],
        isBad = false;

    for(var i=bad.length;i--;){
        if(e.keyCode == bad[i]){
            isBad = true;
            break;
        }
    }

    if(this.value.length > 0 && !isBad){
        refreshWookmark(this.value);
    }
});

This will only run the function u want when input exists and the keyCode is correct, which I think is what you were going for.

Also, 99.9% of the time you can use this.value instead of $(this).val(). This saves the overhead of wrapping this into a jQuery object, then using the internal method to get the value (which is basically this.value).

Upvotes: 0

landons
landons

Reputation: 9547

Couldn't you just break out of the handler if the value is empty?

$(element).keyup(function(e) {
    if (this.value.trim() == '')
        return;

    // do stuff
});

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

You can return on blank input:

$("#idOfElement").keyup(function() {
    if (!this.value == '') {
        //do stuff
    } else {
        return;
    }
});

Upvotes: 0

Related Questions