选择jquery后清除文本框typeahead.js

时间:2015-04-23 22:48:37

标签: jquery typeahead.js

感谢SO上列出的精彩建议,我能够预先确定一个类型,以便在选中时更新表格。我需要做的最后一步是清除选择期间/期间/之后的文本框。我已经尝试在onchange事件中添加内容,拦截select事件等。似乎没有任何工作。我在这里找到的唯一其他参考资料没有答案。有自动完成的响应,但我似乎无法适应它们。任何帮助将不胜感激。

    $(document).ready(function () {

    var ds = [
           @if (ViewData.ModelState.IsValid)
             {
                 var index = 0;
                 foreach (var person in Model)
                 {
                     var jaUser = "{ name: \" " + person.UserName + "\", mobi: \"" + person.MobilePhone + "\" }";
                     if (index > 0) { jaUser = ',' + jaUser; }

                                   @Html.Raw(jaUser)                                       
                     index++;
                 }
             }
    ];

    var d = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        local: ds
    });
    d.initialize();

    $('#contactSearch').typeahead(
{
    hint: true,
    highlight: true,
    minLength: 1,
},
{
    name: 'd',
    displayKey: 'name',
    source: d.ttAdapter(),
    templates: {
        empty: 'not found', //optional
        suggestion: function (el) {
            return "<span onclick=\"addUser2list('" + el.name + "');\"><img src='" + el.mobi + "' />" + el.name + "</span>"
        }
    }
}
);


});


function addUser2list(mobnum){
    if (mobnum.length > 0){
        row = $("<tr></tr>");
        col1 = $("<td>col1</td>");
        col2 = $("<td>"+ mobnum +"</td>");
        col3 = $("<td>col3</td>");
        row.append(col1, col2, col3).prependTo("#mytable");
        //$('#contactSearch').val('');
    }
} 

示例 - 您在文本框中键入“da”,下拉列表中会显示3个名称,您选择1并将其添加到上表中。一旦发生这种情况,我需要清除文本框,目前它显示您选择的名称,您必须手动删除它。由于某些未知原因,jsfiddle没有更新表,但在我的本地代码中它工作正常,我只需要知道如何自动清除“contactSearch”框。

2 个答案:

答案 0 :(得分:18)

您可以使用typeahead:selected从下拉列表中捕获选择项目事件。 There are more events that can be used

  

typeahead:selected - 选择下拉菜单中的建议时触发。将使用3个参数调用事件处理程序:jQuery事件对象,建议对象以及建议所属的数据集的名称。

on('typeahead:selected', function(obj, datum){ //datum will be the object that is selected 
    myTypeahead.typeahead('val','');
    addUser2list(datum);
});

$('.typeahead').typeahead('val','');将清空文本框的值。

这是 DEMO

希望这有帮助。

答案 1 :(得分:0)

添加更新程序

updater: function (item) {
                    comp = map[item];
                    if (typeof comp != 'undefined') {
                        _cid = map[item].myid;                             
                        return '';  // here return blank
                    }
                },
相关问题