2014-07-26 42 views
2

我希望能夠顯示從我的JSON返回的數據在typeahead下拉框中的2個字段,但作爲它們中的一個值使用。不能設置valuekey不同於displaykey在typeahead js

因爲它是,下拉顯示兩個字段,因爲我想和當我選擇一個值的文本框只有一個領域,因爲我想要的。

但是,只要我離開文本框,它將被填充下拉值。

我的HTML場:

<div class="form-group"> 
    <label for="txtlitm">Item Code:</label> 
    <input type="text" class="form-control" id="txtlitm" name="txtlitm" autocomplete="off"> 
</div> 

我的javascript:

$('#txtlitm').typeahead(
{ 
    minLength: 4, 
    highlight: true, 
    hint: false 
}, 
{ 
    displayKey: function(q) { 
     return q.litm + " - " + q.dsc; 
    }, 
    source: function (query, process) { 
     $.getJSON('@VirtualPathUtility.ToAbsolute("~/home/GetItemCodes/")' + query, function (data) { 
      process(data); 
     }); 

    } 
}).on('typeahead:selected', function (obj, data) { 
    $('#txtlitm').val(data.litm); 
}); 

回答

1

使用display,例如

displayKey: 'name', 
display: 'seq', 

valueKey可能不推薦使用。我發現使用display的另一個解決方案,它與jquery-1.12.4typeahead 0.11.1一起使用。我初始化了2 bloodhounds,但只需要一個數據填充我的輸入框。因此,用戶可以輸入ID或名稱,然後單擊建議,然後使用ID填充。