使用bootstrap typeahead填充多个输入

时间:2013-05-28 12:21:55

标签: twitter-bootstrap bootstrap-typeahead

我是新的插入式插件。

我想知道是否可以使用此插件填充2个输入, 详细说来,我有一个文本字段和一个隐藏字段。

数据结构为[{id: int, value: String, tokens: [...]}, ... ]

当用户选择建议时,我想用id基准填充隐藏字段,使用值

填充可见字段

您认为哪个是解决此问题的最佳解决方案?

2 个答案:

答案 0 :(得分:0)

这确实是可能的。非常常见,因为typeahead只处理简单的字符串数组。使用updater - 函数,就像这样

html ,输入内容和隐藏字段

<input type="text" id="typeahead" name="typeahead" placeholder="type some text" data-provide="typeahead">
<input type="hidden" id="hidden" name="hidden">

<强>脚本

//test JSON (doesnt know what you mean by "datum" and what token is)
var json = [
    { 'id' : '1', 'value' : 'value1', 'tokens' : '' },
    { 'id' : '2', 'value' : 'value2', 'tokens' : '' },
    { 'id' : '3', 'value' : 'value3', 'tokens' : '' }
];

//create an array of values for the typeahead
var typeaheadArray = [];
for (var i=0;i<json.length;i++) {
    typeaheadArray.push(json[i].value);
}

//the "magic" goes in the updater-function
// when you select an item from the list, updater looks up the 
// corresponding id and set the value of #hidden to that id 
$(document).ready(function() {
    $("#typeahead").typeahead({
        source: typeaheadArray,
        updater: function(item) {
            for (var i=0;i<json.length;i++) {
                if (json[i].value==item) {
                    $("#hidden").val(json[i].id);
                    return;
                 }
            }
        }
    });
});

答案 1 :(得分:0)

(差不多)OK !! 我修改了这样的处理程序..

_handleSelection: function(e) {
            var byClick = e.type === "suggestionSelected", suggestion = byClick ? e.data : this.dropdownView.getSuggestionUnderCursor();
            if (suggestion) {
                this.inputView.setInputValue(suggestion.value);
                this.inputView.setHiddenValue(suggestion.datum.id); // <-- here is the mod
                byClick ? this.inputView.focus() : e.data.preventDefault();
                byClick && utils.isMsie() ? utils.defer(this.dropdownView.close) : this.dropdownView.close();
                this.eventBus.trigger("selected", suggestion.datum);
            }
        }

我添加了this.inputView.setHiddenValue(suggestion.datum.id);

我将方法定义如下

setHiddenValue: function(value) {
                id = this.$input.attr('id')+'-code';
                $('#'+id).val(value);
            }

和标记...

<input class="span3" type="text" placeholder="Customer" id="customer" name="" value="" >
<input type="hidden" id="customer-code" name="customer" value="" >

也许有一个更清洁的解决方案,欢迎任何反馈......

相关问题