jQuery Key Events with a Search Box

。_饼干妹妹 提交于 2020-01-03 01:46:13

问题


I'm working on an autosuggest plugin with jQuery, and I'd like to add Keypress events so that users can arrow down and up. Also, if they press enter it will add the value to the input.

This is what my HTML looks like:

 <input id="myInput" class="textInput" type="text" name="instructorName"/>
     <label for="search">  </label>
        <div id="myInputResults" class="results" style="display: block;">
           <ul>
            <li><a><div class="suggClass">Suggestion #1</div></a></li>
            <li><a><div class="suggClass">Suggestion #2</div></a></li>
            <li><a><div class="suggClass">Suggestion #3</div></a></li>
            <li><a><div class="suggClass">Suggestion #4</div></a></li>
          </ul>
         </div>

So far, I have something like this:

  $("#myInput").keyup(function (e) { 

     var code = (e.keyCode ? e.keyCode : e.which);

     if (code == 40) {             //If user "keys down"

              //I would want to addClass 'hovered' to the "first <li>"
             // Remove 'hovered' class from any other <li>'s

         }


    });

Up to this point, I'm not quite sure on the proper logic to use so that users can scroll up, down, and press 'enter' to select an item.

Any suggestions and help on this would be greatly appreciated! Thank you.


回答1:


Adding onto Psytronic's code, this should cover the "enter" keycode as well...

$(function(){
  $("#myInput").keyup(function (e) { 
        var code = (e.keyCode ? e.keyCode : e.which);

        if (code == 40) {
            if($("li.hovered").length == 0){
                $("#myInputResults li").eq(0).addClass("hovered");
            }else{
                $("li.hovered").eq(0).removeClass("hovered").next().addClass("hovered");
            }
        };

        if(code == 13) {
            if($("li.hovered").length > 0){
                $("#myInput").val($("li.hovered").eq(0).find("div.suggClass").eq(0).text());
            }
        }
    });
});



回答2:


But I presume that subsequently you want the second "down press" to highlight the second and remove from the first? And so on and so on..

if(!$("li.hovered")){ //if no li has the hovered class
  $("#myInputResults li").eq(0).addClass("hovered");
}else{
  $("li.hovered").eq(0).removeClass("hovered").next().addClass("hovered");
}

This is working on the assumption that there is only one element with the hovered class at any time



来源:https://stackoverflow.com/questions/1583025/jquery-key-events-with-a-search-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!