Question

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

The problem is I'm stucked at this code :

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

It does remove the last element, IF I just clicked the box and then press backspace button. BUT NOT when I clicked inside the box, then clicked outside the box, clicked inside the box again, and re-press backspace key. It deleted/ removed 2 last elements, not only the last element. How could this happen? And how could I fixed it?

Thank you for any responses.

Was it helpful?

Solution

As Felix Kling said - it is because you bind keyup multiple, the fixed code:

if ($('#itemcontainer').html().trim()) {
    $('#searchnama').removeAttr('placeholder');
} else {
    $('#searchnama').attr('placeholder', 'Item');
}

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


    if ($('#itemcontainer').html().trim()) {
        $('#searchnama').removeAttr('placeholder');
    } else {
        $('#searchnama').attr('placeholder', 'Item');
    }
});
$('.remove').bind('click', function() {
    $(this).closest('div.detailwrapper').remove();
});​

also you have common design mistake, - you always use absolute selectors, it can cause many confusions on code just little bigger than this one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top