Event.preventDefault () only works once

When I click the tab button for the first time, it works and the tab is prevented, however, if I click it again right away, it does not fit by default, and I exit the input field.

If I print something, then insert a tab, then enter something else, and then a tab, and then by default it will be prevented every time

The problem is that I cannot insert a tab into a row twice. Any idea what could 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> 
+5
source share
2 answers

By the time keyup , the TAB key may already have completed its task of shifting focus to another element, which means that the keyup event will be fired on that other element instead of being fired on an input field.

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

+2
source

You have a couple of things. You use keyup when you click the tab, on the tab that you call event.preventDefault() , the focus is already moved to the next element. Then you have change change and change listenener, the same as before. In addition, when you click a tab twice a second time, there are no changes, since the property has not changed a second time! You should use keydown instead of keyup and check the trigger order of your events!

+1
source

Source: https://habr.com/ru/post/1259644/


All Articles