thom
thom

Reputation: 159

How to detect 'second backspace' after textbox clear?

I'm trying to make a facebook-like-search (autocomplete), as in facebook's/ gmail's compose message. My whole script is at http://jsfiddle.net/6YbrP/13/.

        if(e.keyCode == 8 && $(this).val() == ''){
            $('#itemcontainer div.detailwrapper:last').remove();
        }

With above script, when I'd like to add more items, I type some chars and erase the chars again using backspace, when the textbox clear it immediately also deleted the last element.

It's not what I want. It shouldn't delete the last element when the textbox clear, unless, users pressed backspace again after the textbox clear. The logic is as in facebook's/ gmail's compose message. SO, what should I do? Any idea to this?

Upvotes: 2

Views: 427

Answers (4)

Anass
Anass

Reputation: 974

This is an other way to do it jsfiddle !! The idea is to add a flag and to store if it's the last removed char or not ! Hope this can help !

var IsLast = false;   
$('#searchnama').keyup(function(e){
    if(e.keyCode == 8 && !this.value && !IsLast){
        $('#itemcontainer div.detailwrapper:last').remove();
    }
    IsLast= this.value;
    });

Upvotes: 0

Rob Cooper
Rob Cooper

Reputation: 28867

Keep track if the input is empty on KeyDown:

$('#searchnama').keydown(function(e){
    $(this).data('empty', !$(this).val());
});

$('#searchnama').keyup(function(e){
    if(e.keyCode == 8 && $(this).data('empty') ){
        $('#itemcontainer div.detailwrapper:last').remove();
    }
});

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

Just use keydown instead of keyup.

$('#searchnama').keydown(function(e){
    if(e.keyCode == 8 && $(this).val() == ''){
        $('#itemcontainer div.detailwrapper:last').remove();
    }
});

Upvotes: 4

MagePal Extensions
MagePal Extensions

Reputation: 17656

preKeycode = '';
$('#searchnama').keyup(function(e){
    if(e.keyCode == 8 && $(this).val() == ''){
        $('#itemcontainer div.detailwrapper:last').remove();
    }

    // check previous key code and current key code
    if(preKeycode == 8 && e.keyCode==8){

    }

    preKeycode = e.keyCode;
});

Upvotes: 0

Related Questions