2012-02-27 68 views
0

我有一個字段「accountname」,它在文本框中使用Jquery autosuggest。這裏當用戶從自動校驗值中選擇並按「Enter Key」填充所選值。 當前我已映射「輸入密鑰」提交表格使用「jquery熱鍵」插件。jquery autosuggest enterkey issue

問題是,只要用戶從autosuggest中選擇了值,他是否按下「Enter」進行選擇。表單正在提交。當用戶在autosuggest下拉列表中按下enterkey時,我不想提交表單。但是當焦點位於自動提示字段時,應該提交表單。

哪個函數需要被覆蓋?

這是我摘錄:

$(document).ready(function() { 
     var availableTags = [ 
      // abbreviations     
      {"label":"academy - acad","value":"acad"},{"label":"accident - acc","value":"acc"},{"label":"account - acct","value":"acct"}]; 

    function split(val) { 
     return val.split(/\s\s*/); 
    } 

    function extractLast(term) { 
     return split(term).pop();   
    } 

    $("#accountName").bind("keydown", function(event) { 
     if (event.keyCode === $.ui.keyCode.TAB && 
       $(this).data("autocomplete").menu.active) { 
      event.preventDefault(); 
     } 

    }).autocomplete({ 
     minLength: 2, 
     autoFocus: false, 

     source: function(request, response) {    
      // delegate back to autocomplete, but extract the last term 
      response($.ui.autocomplete.filter(
        availableTags, extractLast(request.term))); 
     }, 
     focus: function() {    
      // prevent value inserted on focus 
      return false; 
      //return false; 
     }, 
     select: function(event, ui) {    
      var terms = split(this.value); 
      // remove the current input 
      terms.pop(); 
      // add the selected item 
      terms.push(ui.item.value); 
      // add placeholder to get the comma-and-space at the end 
      terms.push(""); 
      this.value = terms.join(" "); 

      // added to trim space 
      $("#accountName").val($.trim($("#accountName").val())); 

      return false; 
     } 
    }); 
}); 
+0

請發佈一個有用的代碼示例。 – DG3 2012-02-27 19:12:18

+0

你能顯示你的代碼嗎? select事件應該只在默認情況下填充文本字段,所以除非你提供了自己的select事件,這就是它應該做的。 – itsmequinn 2012-02-27 19:12:31

回答

3

停止對select事件的autocomplete事件propoagation。

$(".selector").autocomplete({ 
    select: function(event, ui) { 
     event.stopPropagation(); 
    } 
}); 
0

文本輸入字段對按鍵默認行爲是提交表單。

jQuery UI的自動完成的工作方式是在的keydown事件綁定,並檢查是否ENTER而菜單的打開,如果是這樣呼籲event.preventDefault()按鍵被按下。後續的輸入不需要preventDefault(除非菜單再次打開)。

所以這一切都很自然。

我不能說更多沒有看到您的代碼,但我會說:讓jQuery UI處理ENTER鍵,並且,如果您需要綁定在form.submit