Good day to all, I want to do a live search like in Yandex, everything is almost done, but if you go up and down the list of suggested search options with the keyboard keys, the cursor in input goes to the end of the text, then to the beginning. Accordingly, if you press the down key, the cursor will appear at the end of the text in the input field; if you press the up key, the cursor will first appear at the beginning of the text in the input field, and only when you press it again, you will go through the list. Go in quotes because the selection of a phrase in the list is simply imitated by highlighting the color. If you remove the insertion code of the selected text in the input field, then everything is normal, the cursor is in the same place. $('#search').val($("li:eq("+poz+")").text());

Here is a part of the code for "moving" through the list of options for the phrase:

 $('#search').keydown(function(e){ $("ul#resSearch").children().each(function() { $(this).css( "color", "black" ); }); razmer=$("ul#resSearch li").length; if (poz==-1){poz=razmer;} else if (poz==razmer){poz=0;} if (e.keyCode == '40') { $('ul#resSearch').find("li:eq("+poz+")").css( "color", "red" ); $('#search').val($("li:eq("+poz+")").text()); poz++;} if (e.keyCode == '38') { poz--; $('ul#resSearch').find("li:eq("+poz+")").css( "color", "red" ); $('#search').val($("li:eq("+poz+")").text()); } }); 

    1 answer 1

    .preventDefault () Have you heard?

     $('#search').keydown(function(e){ $("ul#resSearch").children().each(function() { $(this).css( "color", "black" ); }); razmer=$("ul#resSearch li").length; if(e.keyCode == '40'||e.keyCode == '38'){ e.preventDefault(); } if(e.keyCode == '40') { poz++; if(poz==razmer){ poz=0; } } if(e.keyCode == '38') { poz--; if(pos==-1){ poz=razmer-1; } } $('ul#resSearch').find("li:eq("+poz+")").css( "color", "red" ); $('#search').val($("li:eq("+poz+")").text()); }); 
    • Thanks, Sir, they helped, the cursor remains in one position, but another question remains: if you go down the list with the key down and then with the key up, you must press the up key twice to highlight the upper phrase and then everything goes well, the phrases are highlighted the first time? - Shura