2011-10-07 60 views
1

這是我的代碼: 我想在自動完成中有一個「標題」,通知用戶有關的一些事情,所以我想用「類別」。 但它不起作用。 顯示「標籤」中的值,但類別不是。 這段代碼有什麼問題? 也許我以錯誤的方式構建availableTags?不過還是自動完成建議標籤...jQuery自動完成 - 類別不顯示,而標籤是

$(function() { 
    var jsonArray = <?php echo $jsonValuesSearch; ?>; 
    var availableTags = [];var i=0; 
      for (var indeks in jsonArray){ 
       var pom = { 
        "label" : jsonArray[indeks], 
        "category" : "Tagi" 
       }; 
       availableTags[i] = pom; 
       i++; 

      } 
    function split(val) { 
        return val.split(" "); 
    } 
    function extractLast(term) { 
     return split(term).pop(); 
    } 

    $("#tags_search") 
     // don't navigate away from the field on tab when selecting an item 
     .bind("keydown", function(event) { 
      if (event.keyCode === $.ui.keyCode.TAB && 
        $(this).data("autocomplete").menu.active) { 
       event.preventDefault(); 
      } 
     }) 
     .autocomplete({ 
      minLength: 0, 
      source: function(request, response) { 
       // delegate back to autocomplete, but extract the last term 
       response($.ui.autocomplete.filter(
        availableTags, extractLast(request.term))); 
      }, 
      focus: function() { 
       // prevent value inserted on focus 
       return false; 
      }, 
      select: function(event, ui) { 
       var terms = split(this.value); 
       // remove the current input 
       terms.pop(); 
       // add the selected item 
       terms.push(ui.item.value); 
       // add placeholder to get the comma-and-space at the end 
       terms.push(""); 
       this.value = terms.join(" "); 
       return false; 
      } 
     }); 
}); 

這是我如何創建JSON表:

$items = Doctrine::getTable('Tags')->findAll()->toKeyValueArray('id', 'name'); 
    $this->view->jsonValues = Zend_Json_Encoder::encode($items); 

回答

1

當jQuery的UI自動完成對人們將JSON標籤:和值:,它顯示在標籤項目下拉菜單,選中時,它將值項目設置爲輸入框的值。你可以有其他的東西,比如category :,就你的情況而言。你的select:選項有this.value和item.value,但你的JSON沒有價值: - 所以Autocomplete不知道在select中做什麼。如果您希望在下拉框中顯示標籤項目和類別項目,則需要一個成功:選項,並使用表達式按照您的方式將它們連接起來。查看Autocomplete文檔頁面中的源代碼,瞭解如何執行此操作的一些示例。然後,只需替換你想要的序列和標點符號中的變量。

+0

感謝您的回答,但我仍然不明白,爲什麼上面的代碼不工作,事實上我試圖找到文檔中的答案...我應該更改PHP中的代碼,我在哪裏創建數組? – rukya

+0

使用jsonlint.com查看您的JSON是否具有適當的格式。您需要在自動填充中使用dataType = JSON。您的選擇選項有未定義的術語 - item.value和this.value - 因爲您的數組沒有標記爲值。等我建議你從一個更簡單的自動完成從某處複製 - 無需搜索,extractLast,拆分等。獲取該工作,然後逐步添加功能。對不起,我無法修復你的代碼,因爲我不明白你想做什麼,它有多個問題。 –

+0

好的,謝謝,我終於搞定了:) – rukya