简体   繁体   中英

auto-suggest keyboard event not working on keyup event

I am creating auto-suggest from scratch. I am using jquery-ajax function to get the data from server. I am doing filtering data on keyup event for auto suggestion.

Now after filtering I want to navigate the list items using keyboard's arrow keys but the problem is every time I am pressing the arrow key the list is being refreshed on keyup event which clears the selection happened through arrow key.

I track trace my code and I came to know this reason. Here is my code :

var $listItems = $('li.suggestion-item');
   var key = event.keyCode,$current,
   $selected = $listItems.filter('.selected');
   if ( key != 40 && key != 38 ) { return key; }
   $listItems.removeClass('selected');
   switch(key){    
     case 40: // Down key
       if (! $selected.length || $selected.is(':last-child')) {
            $current = $listItems.eq(0).addClass('selected');
       }
       else {
            $current = $selected.removeClass('selected').next().addClass('selected');
       }
           break;
       case 38: // Up key
       if ( $selected.length ===1 || $selected.is(':first-child') ) {
            $current = $listItems.last();
       }
       else {
          $current = $selected.prev();
       }
       break;
       case 13:
            $('.suggestion-item, .error').hide();
            break;      
    }
    } else {
          $('#validline').removeClass('true');
          $('.suggestion-item, .error').hide();      
     }
 }

can anybody suggest me the solution of this problem?

Try like this,

$("#inputField").keyup(function(){
    if(keycode!=38 || keycode!=40){
        //proceed to fetch suggestion...
    }else{
        //proceed navigation..
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM