如何在发送到twitter预先搜索引擎之前更改输入值

时间:2015-03-17 09:00:17

标签: javascript jquery twitter-typeahead

当用户在输入字段中输入时,我正在尝试将小写字母更改为大写。然后,输入字段的值将用作typeahead搜索引擎的关键字。

问题是,当我为typeahead添加一个事件监听器时,输入值将变为键入字母的大写和小写。

$(document).ready(function(){
var suggestionsArray = ["audi", "porsche", "pagani", "mercedes benz", "bmw" , "bugatti"];
var descs = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: $.map(suggestionsArray, function(desc) { return { value: desc }; })
});

var quicksearchInput = $("#in");

// kicks off the loading/processing of `local` and `prefetch`
descs.initialize();

quicksearchInput.on('keypress', function(event) {
    var val = this.value;
    event = event || window.event;

    var charCode = typeof event.which == "number" ? event.which : event.keyCode;
    if (charCode && charCode != 13 && charCode != 32 && charCode != 8) {        

        var keyChar = String.fromCharCode(charCode).toUpperCase();

        var mappedChar =  keyChar;          

        var start, end;
        if (typeof this.selectionStart == "number" && typeof this.selectionEnd == "number") {
            start = this.selectionStart;
            end = this.selectionEnd;
            this.value = val.slice(0,start) + mappedChar + val.slice(end);

            this.selectionStart = this.selectionEnd = start + 1;
            $("#dbekar").typeahead('val', this.value);

        }
    }
})
.typeahead({
    hint: true,
    highlight: true,
    minLength: 0
}, {
    name: "noname",
    displayKey: "value",
    source: descs.ttAdapter(),
    templates: {
        empty: [
          '<div class="empty-message">',
          'No matching results found',
          '</div>'
        ].join('\n')
    }
    });
});

此处jsfiddle

1 个答案:

答案 0 :(得分:1)

我找到了解决问题的方法。我删除了输入的事件处理程序,添加了自定义源函数并操作了typeahead的查询变量,将字母更改为大写。

$(document).ready(function(){
var suggestionsArray = ["audi", "porsche", "pagani", "mercedes benz", "bmw" , "bugatti"];
var descs = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: $.map(suggestionsArray, function(desc) { return { value: desc }; })
});

var quicksearchInput = $("#in");

// kicks off the loading/processing of `local` and `prefetch`
descs.initialize();

quicksearchInput.typeahead({
    hint: true,
    highlight: true,
    minLength: 0
}, {
    name: "noname",
    displayKey: "value",

    source: function (query, cb) {
        query = query.toUpperCase();
        $("#in").typeahead('val', query);
        descs.get(query, function (suggestions) {
          cb(suggestions.slice(0, 5));
        });
    },

    templates: {
        empty: [
          '<div class="empty-message">',
          'No matching results found',
          '</div>'
        ].join('\n')
    }

    });
}); 

解决方案在jsfiddle