【问题标题】:adding custom function to bootstrap typeahead将自定义函数添加到 bootstrap typeahead
【发布时间】:2012-12-19 20:22:47
【问题描述】:

我正在使用 typeahead 来提取名称,然后使用与名称相对应的 id 更新隐藏字段。在我的表格中,名称可以留空,不需要填写。

有没有办法在 typeahead 函数中添加自定义错误检查?例如,我开始填写表格并输入/选择一个用户,然后我改变主意并想将其留空。至此,用户 ID 已经添加到隐藏字段中,因此即使我将名称字段留空,表单也会在其中传递用户 ID。

我想我总是可以在提交时进行错误检查,但我很好奇是否有办法添加到本机 api。

我的代码是:

$('#name_field').typeahead({
        minLength: 3,
        source: function (query, process){

            $.get('/url/getsource', {query: query}, function (data) {                   
                names = [];
                map = {};
                $.each(data, function (i, name) {
                    map[name.uName] = name;
                    names.push(name.uName);
                });
                process(names);                 
            });             
        },
        matcher: function (item) {
            if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
                return true;
            }
        },
        sorter: function (items) {
            return items.sort();
        },
        highlighter: function (item) {
            var regex = new RegExp( '(' + this.query + ')', 'gi' );
            return item.replace( regex, "<strong>$1</strong>" );
        },
        updater: function (item) {
            selectedID = map[item].id;              

            $('#id_field').val(selectedID);
            return item;
        }

    });

我希望我可以添加类似的东西

$('#name_field').typeahead({
    myCustom: function (){
        if($('#name_field').val() == ''){
            $('#id_field').val('');
     },
     rest, 
     of the,
     function
 });

【问题讨论】:

    标签: javascript jquery twitter-bootstrap bootstrap-typeahead typeahead


    【解决方案1】:

    您可以将函数绑定到用户字段的模糊事件。因此,一旦用户对另一个表单元素进行任何更改(如果它留空),您就会清除 typeahead 字段。

    $('#user-field').blur(function (e) {
       if(this.val() === ''){
            $('#typeahead-field').val(''); // Clear typeahead
       }
    });
    

    【讨论】:

    • 并使该函数独立于 .typehead() ?
    • 是的,您必须这样做,因为使用独立 API 无法做到这一点
    • 将其链接到 .typeahead (之前或之后)或保持完全独立是否有任何意义?
    • 似乎没有什么意义,因为您想观察另一个元素并单独更新 typeahead 字段。
    猜你喜欢
    • 1970-01-01
    • 2014-10-14
    • 2010-10-31
    • 2021-07-23
    • 1970-01-01
    • 2023-03-30
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多