Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

event.preventDefault() only works once

When I press the tab button the first time, it works and tab is prevented, however if i press it again straight away, the default is not prevented, and I tab out of the inputbox.

If I type something then tab then type something else then tab, then it is default is prevented everytime

The problem is I can't tab twice in a row. Any idea what might be the problem?

 $("#functionSearch").on("change propertychange keyup",function( event ) {
    event.preventDefault();
    console.log(event)
    if (event.which == 9 ) {
        console.log("TAB")
    }else{
        clearHighlight();
        var input = $(this).val();
        if(input.length > 0){
            filteredArr = jQuery.grep(linksArr, function( val, index ) {
                return ( val.toLowerCase().indexOf(input.toLowerCase()) != -1);
            });
            selectElements(filteredArr);
        }
    }

});

// MAY BE USEFUL
function selectElements(filteredArr){
    $(filteredArr).each(function( index, link){
       var id = link.split("~")[1]
       $("#"+id).addClass("selected");
    });
    highlightFirstElement();
    }

    function highlightFirstElement(){
        $(".selected").first().addClass("highlighted");
    }

    function highlightNextElement(){
        $(".selected").next().addClass("highlighted");
    }

    function clearHighlight(){
        $(".highlighted").removeClass("highlighted");
        $(".selected").removeClass("selected");
    }

<div id="functionSearchDiv" class="funSearch">
    <input type="text" id="functionSearch"></input>
</div>
like image 723
code511788465541441 Avatar asked Oct 18 '22 22:10

code511788465541441


1 Answers

By the time keyup is fired, the TAB key may have already done its job of displacing the focus to another element, meaning that the keyup event will be fired on that other element instead of being fired on the input field.

The simplest solution is to listen to keydown instead of keyup (see working fiddle).

like image 131
Shawn Avatar answered Oct 21 '22 09:10

Shawn