2012-09-17 30 views
0

如何讓用戶打開下拉列表,然後鍵入幾個字母以跳轉到正確的項目?我需要實現自己的搜索邏輯,因爲格式是固定的,並且不可按原樣搜索(所有都以一個開放的括號開頭),但我不確定如何鉤住行爲。 Jquery是首選,但任何可以跨瀏覽器工作的東西都可以。按鍵根據自定義搜索跳轉到DropDownList中的項目

例子:

(AABE)能夠空調

(BAE)樹皮航空設備

鍵入 'BA' 應轉移到第二項,等等

謝謝!

+0

我相信你可以聽KeyPress事件,改變selectedIndex設置爲找到的項目。 – Casperah

回答

1

在jQuery中,您可以使用keydown事件。下面的代碼可以住在這裏看到:http://jsfiddle.net/TXZWC/26/

HTML:

<select name="companies"> 
    <option value="">choose</option> 
    <option value="1" data-search-match="AABE">(AABE) Able Air Conditioning</option> 
    <option value="2" data-search-match="BAE">(BAE) Bark Air Equipment</option> 
</select> 

<a id="clear-search" href="#">Clear Search</a> 

JS:

$(document).ready(function(){ 

    var $select = $('select'), 
     searchQuery = ''; 

    $(document).on('keydown', function (e){ 

     // get the char value and append to search string 
     searchQuery += String.fromCharCode(e.which); 

     // unselect previously selected option 
     deselectSelectedOption(); 

     // find matching option     
     var $selected = $select.find('option').filter(function(){    
      return $(this).data('search-match') === searchQuery; 
     }); 

     if($selected){ 
      $selected.attr('selected', 'true'); 
     }      
    });  

    $('#clear-search').click(function(e){ 
     e.preventDefault(); 
     searchQuery = '';       
     deselectSelectedOption(); 
     $select.find('option').first().attr('selected', 'true'); 
    }); 

    function deselectSelectedOption(){ 
     $select.find('option[selected]').removeAttr('selected');  
    }   
});​ 
+0

謝謝,儘管JSFiddle示例在Chrome中不適用於我。 –

+0

我更新了代碼。請現在嘗試。 – Gho5t

+0

謝謝,但這似乎並不奏效。試過IE和Chrome。 –