2013-04-14 79 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; 
});