简体   繁体   English

将自定义功能添加到引导程序提前

[英]adding custom function to bootstrap typeahead

I'm using typeahead to pull names and then updating a hidden field with the id respective to the name. 我正在使用typeahead提取名称,然后使用名称对应的id更新隐藏字段。 In my form the name can be left blank, filling it is not a requirement. 在我的表单中,名称可以保留为空白,不需要填写。

Is there a way to add custom error checking to the typeahead function? 有没有一种方法可以向typeahead函数添加自定义错误检查? for instance, I start filling out the form and type/select a user, then I change my mind and want to leave it blank. 例如,我开始填写表格并键入/选择一个用户,然后我改变主意并希望将其留空。 by this point, the user id is already added to the hidden field, so even if i leave the name field blank, the form will be passed with the user id in it. 至此,用户ID已经添加到了隐藏字段中,因此即使我将名称字段留为空白,表单也将通过其中的用户ID进行传递。

I guess I can always do error checking on submit, but am curious if there is a way to add to the native api. 我想我总是可以在提交时进行错误检查,但很好奇是否有添加到本机api的方法。

my code is: 我的代码是:

$('#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;
        }

    });

I was hoping I can add something like 我希望我可以添加类似

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

You could bind a function to the blur event of the user field. 您可以将函数绑定到用户字段的blur事件。 So as soon as the user makes any changes to another form element if it is left blank you clear the typeahead field. 因此,如果用户对另一个表单元素进行了任何更改(如果将其保留为空白),则请清除预输入字段。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM