Search code examples
javascriptjquerybootstrap-typeahead

Bootstrap Typeahead click event


I'm using bootstrap-typeahead.js v2.0.0 for an autocomplete search. I have a click event to view the result but it only works like 1 of 10 times, in the other case I get an error: "Uncaught SyntaxError: Unexpected token u".

I've looked around and found this: https://github.com/twitter/bootstrap/issues/4018 and I tried the solutions there but nothing seems to work. It works perfect when I use the enter-key so it has to be something concerning the click-event. Anyone else got the same problem? Code:

$('#search').typeahead({

        source: function (typeahead, query) {
                $.ajax({
                    type: "GET",
                    url: "search/" + query,
                    success: function (data) {
                        searchResult = data;
                        return typeahead.process(data);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        console.log(thrownError);
                    }
                }); 
        }
        },
        onselect: function (obj) {
            window.location.href = "view/" + obj.id;
        },
        items: 8,
        minLength: 1,
        highlighter: function (item) {
        var artist = _.find(searchResult, function (a) {
            return item === a.value;
        });
        return ('<li>' + artist.value + ' (' + artist.dbirth + '-' + artist.ddeath + ')<li>');
        }
    });

Solution

  • Okay I solved it myself. This is what you have to do:

    Open bootstrap-typeahead.js and find the listen method on row 203 and modify like this:

        listen: function () {
        this.$element
        .on('blur',     $.proxy(this.blur, this))
        .on('keypress', $.proxy(this.keypress, this))
        .on('keyup',    $.proxy(this.keyup, this))
    
        // if ($.browser.webkit || $.browser.msie) {
        this.$element.on('keydown', $.proxy(this.keypress, this))
        // }
    
        this.$menu
        .on('click', $.proxy(this.click, this))
        .on('mouseenter', 'li', $.proxy(this.mouseenter, this))
        .on('mouseleave', 'li', $.proxy(this.mouseleave, this))
        }
    

    The only difference here is that I added a listener on 'mouseleave'.

    Go to the mouseenter method on row 278 and change it to this:

    mouseenter: function (e) {
          $(e.currentTarget).addClass('active')
        }
    

    Then add a new method named 'mouseleave' and add this code:

    mouseleave: function () {
          this.$menu.find('.active').removeClass('active')
    }
    

    Hopefully this will help anyone with a similar problem.