javascript - Toggle up/down with up down keys in auto suggest -


i trying make auto-suggest using ajax php , mysql. auto-suggest working getting problem toggling down down keys. following jsfiddle example completing work. can't why navigate function been called twice. because alerts twice when press down keys.

jquery

 var navigate = function(diff){    displayboxindex += diff;      var oboxcollection = $("#searched .searchfull");      if (displayboxindex >= oboxcollection.length) {         displayboxindex = 0;         alert("a");     }     if (displayboxindex < 0) {         displayboxindex = oboxcollection.length - 1;         alert("b");     }     var cssclass = "selected";     oboxcollection.removeclass(cssclass).eq(displayboxindex).addclass(cssclass);  } $(document).on('keypress keyup', "#search", function (e) {     if (e.keycode == 13 || e.keycode == 32) {         $('.display_box_hover').trigger('click');         return false;     }     if (e.keycode == 40) {         //down arrow         navigate(1);     }     if (e.keycode == 38) {         //up arrow         navigate(-1);     } }); 

html

 <div id="searched" style="display: block;">    <a href="http://localhost/c2c/init/product/78">       <div class="searchfull">    </a>    <a href="http://localhost/c2c/init/product/77">       <div class="searchfull">    </a>    <a href="http://localhost/c2c/init/product/76">       <div class="searchfull">    </a>    <a href="http://localhost/c2c/init/product/73">       <div class="searchfull">    </a> 

here solution issue:

you call 2 events like: keypress , keyup. so, call twice. remove 1 here remove keypress , here works well.

$(document).on('keyup', function (e) {         if (e.keycode == 13 || e.keycode == 32) {             $('.display_box_hover').trigger('click');             return false;         }         if (e.keycode == 40) {             //down arrow             //alert("down");             navigate(1);         }         if (e.keycode == 38) {             //up arrow             navigate(-1);         }     }); 

check fiddle here.

and per comment here selected class not removed checked in firebug. see below image.

enter image description here

hope helps.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -