Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twitter Bootstrap Typeahead to function like Google Chrome Omnibox

Love the Twitter Bootstrap typeahead functionality but I have a small tinkering I'd like to do - I want to have the best match (or first match is probably simpler) result in the drop-down be autofill in the input box.

The functionality I'm looking for is exactly the way the Google Chrome Omnibox works

screenshot

Anyone know of a solution for this?

like image 810
Ryan Grush Avatar asked Nov 28 '25 04:11

Ryan Grush


1 Answers

Playing a bit, I come up with that code.

Live demo (jsfiddle)

$('.omnitype').each(function() {
    var $omnitype = $(this);
    $omnitype.typeahead({
        source: mySource,
        items: 4,
        sorter: function(items) {
            // Bootstrap code
            /* ... */
            // Modified code (delay the return of sorted)
            var sorted = beginswith.concat(caseSensitive, caseInsensitive);

            // if there is a first element, we fill the input select what we added
            var first = sorted.length && sorted[0];
            if (first) {
                var origin = this.$element.val();
                this.$element.val(first);
                createSelection(this.$element.get(0), origin.length, first.length);
            }

            // back to the intended behavior
            return sorted;
        }
    });
});

I used this answer to provide the createSelection function (not sure if really needed).

Still needs quite some tweaking, as the keys doesn't work as expected. It may be easier to recode the whole plugin with some checking that would give naturally the intuitive behavior.

Or you may be able to catch the key events before the plugin and do what is appropriate.

like image 57
Sherbrow Avatar answered Nov 30 '25 17:11

Sherbrow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!