2011-03-23 47 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”); ?