Dodinas
Dodinas

Reputation: 6805

jQuery Key Events with a Search Box

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.

Upvotes: 1

Views: 3911

Answers (2)

WesleyJohnson
WesleyJohnson

Reputation: 1538

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());
            }
        }
    });
});

Upvotes: 2

Psytronic
Psytronic

Reputation: 6113

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

Upvotes: 2

Related Questions