Search code examples
jquerytwittertypeaheadbloodhound

Twitter Typeahead Bloodhound: Get current search string inside sorter option


I'm trying to sort the suggestions depending on the position of the search string inside the data-fields. If someone types 'ar' the suggestion A:'how are you' should be ordered before B:'come as you are' because the search string matches at the 2nd word in A and at the 4th word in B. That already works very well.

To get the search string I use $('.searchfield').val(). The problem is, that I have multiple search fields inside the pages, so I have to know which search-field is currently used.

Here is my code inside the bloodhound declaration:

sorter: function(a, b) {
        var input_string = $('.searchfield').val(); // <-- Here is my problem
        input_string = input_string.split(/[ \-]+/);
        input_string = input_string[0].toLowerCase();
        var aArray = a.name.toLowerCase().split(/[ \-]+/);
        var bArray = b.name.toLowerCase().split(/[ \-]+/);
        var apos = 0, bpos = 0;
        for (var i = 0; i < aArray.length; i++) {
            if (aArray[i].indexOf(input_string) !== -1) {
                apos = i;
                break;
            }
        }
        for (i = 0; i < bArray.length; i++) {
            if (bArray[i].indexOf(input_string) !== -1) {
                bpos = i;
                break;
            }
        }
        if (apos < bpos) {
            return -1;
        } else if (apos > bpos) {
            return 1;
        } else return 0;
    }

Has anyone an idea how to get the search string of the currently used input field?

Thank you,

Bernd

P.S. Sorry for my english


Solution

  • Ok, I defined a global variable and when an input field gets focus I save the element into the variable.

    var currentTypeAheadField = null;
    
    jsTypeahead.on('focus', function() {
        currentTypeAheadField = $(this);
    })
    

    So in my Bloodhound declaration I have access to the value:

    sorter: function(a, b) {
        var input_string = currentTypeAheadField.val();
        ...
    }
    

    Didn't find a better solution, but it works.