2011-01-14 20 views
3

我需要一個在rails應用程序中使用自動完成。它使用組合框作爲源。我使用jquery自動完成和組合框。爲rails應用程序jquery自動完成

但我需要一個額外的功能。假設我們鍵入「Apple」,並且它在自動完成搜索中不可用,它將在名爲「Create New Apple」的列表中顯示一個新項目,如果我們選擇它,將觸發JavaScript事件。這樣我們可以打開一些對話框來添加它。

此外,自動完成也可以在渲染後更新。意思是如果我們添加新記錄,它也可以填充到列表中。

希望能從你們那裏得到好東西。

回答

4

我用這段代碼完整填充了我的場景。我修改了jquery站點的代碼,將重構事件重構爲。

auto_obj.change = function(event, ui) { 
     if (!ui.item) { 
     var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"), 
        valid = false; 
     select.children("option").each(function() { 
     if ($(this).text().match(matcher)) { 
      this.selected = valid = true; 
       return false; 
     } 
     }); 
     if (!valid) { 
      // Trigger the event for value not found 
      $(select).trigger('autocompletenotfound', $(this).val()); 

      // remove invalid value, as it didn't match anything 
      $(this).val(""); 
      select.val(""); 
      input.data("autocomplete").term = ""; 
      return false; 
     } 
    } 
} 

,並在源功能

auto_obj.source = function(request, response) { 
       var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i"); 
       var match = false; 

       response(select.children("option").map(function(i, value) { 
        var text = $(this).text(); 
        if (this.value && (!request.term || matcher.test(text))) { 
         match = true; 
         return { 
          label: text.replace(
            new RegExp(
              "(?![^&;]+;)(?!<[^<>]*)(" + 
                $.ui.autocomplete.escapeRegex(request.term) + 
                ")(?![^<>]*>)(?![^&;]+;)", "gi" 
              ), "<strong>$1</strong>"), 
          value: text, 
          option: this 
         }; 
        } 
        if (!match && i == select.children("option").size() -1 && self.options.allow_new) { 
         return { 
          label:'Create new <strong>'+ input.val() +'</strong>', 
          value: input.val(), 
          option: null 
         }; 
        } 
       })); 
      }; 

這符合我的要求。希望對其他人有幫助。

1

您是否從服務器端或客戶端獲得自動完成查詢的響應?

如果響應來自服務器端,添加一個新的「蘋果」會自動更新。至於javascript事件觸發一個新的對話框,你可以使用Jquery「change」觀察者事件。

事情是這樣的:

 

$("#autocomplete-list").live("change",function(){ 
    if($(this).val() == "Create New Apple"){ 
     //add function to create dialogue 
    } 
}); 
 

現在,如果你自動完成響應是從客戶端,您可以使用上面的回調觸發對話框創建。

但要動態更新自動填充響應以包含新創建的「apple」,您將不得不替換保存所有蘋果的javascript變量。

無論何時創建一個新的「apple」,它將替換變量所在的DOM元素,您都可以通過調用rails應用程序來完成此操作。這樣,創建的新「蘋果」就會包含在自動完成列表中。

希望這是有道理的