2012-07-27 119 views
24

我正在使用JQuery UI自動完成。一切都按預期工作,但是當我用鍵盤上的向上/向下鍵循環時,我注意到文本框中充滿了列表中的項目,但是當我到達列表的末尾並再次按下向下箭頭時時間,我輸入的原始術語顯示出來,它基本上允許用戶提交該條目。JQuery自動完成:如何強制從列表中選擇(鍵盤)

我的問題:是否有簡單的方法來限制選擇到列表中的項目,並從鍵盤選擇中刪除輸入中的文本?例如:如果我有一個包含{'Apples (AA)', 'Oranges (AAA)', 'Carrots (A)'}的列表,如果用戶鍵入'app',我將自動選擇列表中的第一個項目('蘋果(AA)'),但如果用戶按下箭頭,'app'再次出現在文本框中。我怎樣才能防止呢?

謝謝。

+0

每次加載列表它會激發事件。檢查是否只有一個元素,然後觸發一個'click'事件或選擇項目 – Imdad 2012-07-27 04:08:25

+0

我總是選擇第一個項目,但如果我使用鍵盤循環顯示列表,它將顯示文本框中的文本當我到達列表的末尾時。這就是我想要阻止的;基本上,我希望它回到列表的頂部。 – 2012-07-27 04:28:25

+1

'focus:function(event,ui){return false; return false; }' – Imdad 2012-07-27 04:31:05

回答

3

"Before focus is moved to an item (not selecting), ui.item refers to the focused item. The default action of focus is to replace the text field's value with the value of the focused item, though only if the focus event was triggered by a keyboard interaction. Canceling this event prevents the value from being updated, but does not prevent the menu item from being focused."

reference

焦點事件:

focus: function(e, ui) { 
    return false; 
} 
+0

謝謝。這可以防止鍵盤導航填充文本框,這完全繞過了問題。 – 2012-07-27 04:47:07

+0

@AliB不客氣:) – 2012-07-27 04:47:50

+0

好了,在插入它之後,它解決了部分問題:當我用箭頭鍵滾動時,文本框不再被填充,但我仍然能夠返回因爲向下鍵有一個「額外」插槽,將焦點從列表中移出。我需要它專門留在列表中。有任何想法嗎? – 2012-07-27 05:05:49

36

爲動力的選擇,你可以使用自動完成

"change" event
 var availableTags = [ 
      "ActionScript", 
      "AppleScript" 
     ]; 
     $("#tags").autocomplete({ 
      source: availableTags, 
      change: function (event, ui) { 
       if(!ui.item){ 
        //http://api.jqueryui.com/autocomplete/#event-change - 
        // The item selected from the menu, if any. Otherwise the property is null 
        //so clear the item for force selection 
        $("#tags").val(""); 
       } 

      } 

     }); 
+0

工作得很好 – thepk 2013-06-07 15:27:07

+2

這個解決方案的問題是,如果有人在字段中鍵入非法值,然後命中輸入,表單將提交非法值。仍試圖找到一個優雅的解決方案。 – gitb 2014-04-30 20:06:12

+0

一個可能的解決方案是從表單中移除'type =「submit」',並使用jQuery來處理提交按鈕上的點擊事件。最後,服務器端驗證是您唯一真正信任的東西。 – Sky 2017-01-22 17:13:11

9

無論在梳子這些其他的答案工作得很好。

另外,您可以使用event.target來清除文本。這有助於在向多個控件添加自動完成功能或不想在選擇器中輸入兩次時出現(可維護性問題)。

$(".category").autocomplete({ 
    source: availableTags, 
    change: function (event, ui) { 
     if(!ui.item){ 
      $(event.target).val(""); 
     } 
    }, 
    focus: function (event, ui) { 
     return false; 
    } 
}); 

應該指出,然而,在即使「焦點」返回false,上/下鍵仍然會選擇該值。取消此事件僅取消文本的替換。所以,「j」,「down」,「tab」仍然會選擇與「j」匹配的第一個項目。它不會在控制中顯示它。

+0

工作很好。謝謝! – ajbraus 2014-08-07 17:06:22

+0

這大部分工作。我正在使用ajax源代碼,並且如果用戶在加載選項之前點擊選項卡,則更改不會清除結果。 – danielson317 2016-11-09 16:50:32

2

定義一個變量

var inFocus = false; 

以下事件添加到您的輸入

.on('focus', function() { 
    inFocus = true; 
}) 
.on('blur', function() { 
    inFocus = false; 
}) 

而一個keydown事件附加到窗口

$(window) 
    .keydown(function(e){ 
     if(e.keyCode == 13 && inFocus) { 
      e.preventDefault(); 
     } 
    }); 
相關問題