2011-03-23 46 views
1

問候,取消表單上的JQuery UI自動完成提交

我有一個jqueryui自動完成輸入,它使用ajax調用填充建議。如何確保表單提交時,不會出現建議?我嘗試過調用「close」方法,但這不起作用,因爲表單可能在ajax調用完成之前提交。

我創建了一個小提琴在這裏展示我的問題: http://jsfiddle.net/P7VJf/5/

這是基於jQueryUI的演示在這裏: http://jqueryui.com/demos/autocomplete/#remote-jsonp

下面是代碼:

$(function(){  
    $('form').submit(function(){ 
     /* 
      when the form is submitted, i want to cancel auto complete 
      if the ajax call hasn't completed, the suggestions 
      will still show even if we call close here 
     */ 
     $("#city").autocomplete("close");   
     $('span').html(Math.random() * 3); 
     return false; 
    }); 

    $("#city").autocomplete({ 
     delay: 300, 
     source: function(request, response) { 
      $.ajax({ 
       url: "http://ws.geonames.org/searchJSON", 
       dataType: "jsonp", 
       data: { 
        featureClass: "P", 
        style: "full", 
        maxRows: 12, 
        name_startsWith: request.term 
       }, 
       success: function(data) { 
        response($.map(data.geonames, function(item) { 
         return { 
          label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName, 
          value: item.name 
         } 
        })); 
       } 
      }); 
     }, 
     minLength: 2 
    });   
}); 

任何幫助不勝感激。

回答

2

建立在Xnake的答案上,我已經通過使用'destroy'命令來工作。麻煩的是,這完全殺死了自動完成,所以你需要重新配置它。我通過將初始調用自動完成重構爲一個單獨的函數,然後在destroy命令之後再次調用它來完成此操作。像這樣:

function configureAutocomplete() { 

    $("#city").autocomplete({ 
     delay: 300, 
     source: function(request, response) { 
      $.ajax({ 
       url: "http://ws.geonames.org/searchJSON", 
       dataType: "jsonp", 
       data: { 
        featureClass: "P", 
        style: "full", 
        maxRows: 12, 
        name_startsWith: request.term 
       }, 
       success: function(data) { 
        response($.map(data.geonames, function(item) { 
         return { 
          label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName, 
          value: item.name 
         } 
        })); 
       } 
      }); 
     }, 
     minLength: 2 
    });   
} 

$(function(){  
    $('form').submit(function(){ 
     /* 
      when the form is submitted, i want to cancel auto complete 
      if the ajax call hasn't completed, so destroy the existing 
      autocomplete and set up a new one 
     */ 
     $("#city").autocomplete("destroy"); 
     configureAutocomplete(); 
     $('span').html(Math.random() * 3); 
     return false; 
    }); 

    configureAutocomplete(); 
}); 
1

您是否試過使用destroy來代替:例如:$(「#city」)。autocomplete(「destroy」); ?