2013-04-14 76 views
0

我想在jQuery自动完成未找到结果时禁用我的提交。我现在工作的一半,我算我的结果很好。jQuery自动完成:当无结果时禁用提交

唯一的问题是当我有一个结果,我提交,结果回弹到0,所以我不能提交。我想在提交时记住自动完成计数值。

我算我的结果:

$('#stock_input').autocomplete({ 

     source:'autocomplete.php', 
     autoFocus: true, 
     minLength:1, 
    open: function(event,ui){ 
      count = $(this).autocomplete("widget").find("li").length; 
      $('#count').text(count); 
    }, 
    close: function(event,ui){ 
      count = 0; 
      $('#count').text(count); 
    } 
}); 

Allowsubmit设置:

var allowSubmit = true; 
     $("#updatestock_form").submit(function(e){ 
      if(count === 0){ allowSubmit = false; alert(count); } 
      else { allowSubmit = true; alert(count); } 
      if (!allowSubmit) return false; 

     //rest of submit code 
     }); 

回答

1

与您的代码的问题:

close: function(event,ui){ 
      count = 0; 
      $('#count').text(count); 
    } 

this will make count = 0每次您关闭自动完成

当您提交形成计数VAR将始终为0,这使得allowSubmit = false

$("#updatestock_form").submit(function(e){ 
      if(count === 0){ allowSubmit = false; alert(count); } 
      else { allowSubmit = true; alert(count); } 
      if (!allowSubmit) return false; 

     //rest of submit code 
     }); 

您可以检查此上提交自己

$("#updatestock_form").submit(function(e){ 
      var count = $('#stock_input').autocomplete("widget").find("li").length; 
      if(count === 0){ allowSubmit = false; alert(count); } 
      else { allowSubmit = true; alert(count); } 
      if (!allowSubmit) return false; 

     //rest of submit code 
     }); 
+0

谢谢,这是一个好主意,检查提交本身。但是,当我删除关闭标记,计数从未获得0,它停留在最后一个计数 – Edwin

+0

他们是没有必要删除'关闭',你可能需要这一些其他功能 –

+0

嗯..但我从来没有计算0的结果。如果我输入“BBB”,我得到3(正确)reults,然后我输入“BBBB”,这应该给我例如0结果,计数器停留在3结果。只有当结果为0时才会发生这种情况。如何在没有结果时将计数器正确设置为0? – Edwin

0

我用下面的代码做了它:

$('#stock_input').autocomplete({ 
     source:'autocomplete.php', 
     autoFocus: true, 
     minLength:1, 
     response: function(event, ui) { 
      if (ui.content.length === 0) { 
       count_result = 0; //no results 
      } else { 
       count_result = 1; 
      } 
     } 
}); 

And:

$("#updatestock_form").submit(function(e){ 
    if(count_result === 0){ allowSubmit = false; } 
     else { allowSubmit = true; } 
     if (!allowSubmit) return false; 
});