Typeahead.js include dynamic variable in remote url

I believe the accepted answer is now out of date. The remote option no longer has replace. Instead you should use prepare:

$('#programme').typeahead({
    remote: {
        url: 'typeahead.php?programme&type=1&school_name=',
        prepare: function (query, settings) {
            settings.url += encodeURIComponent($('#school').val());

            return settings;
        }
    }
});

One issue I ran into was pulling the value from another typeahead object. Typeahead essentially duplicates your input, including all classes, so you have two nearly identical objects, one with the tt-hint class and the other with tt-input. I had to specify that it was the tt-input selector, otherwise the value I got was an empty string.

$('.field-make').val();  // was "" even though the field had a value
$('.field-make.tt-input').val();  // gave the correct value

Bloodhound remote options


I have found the solution! Code:

$('#programme').typeahead({
    remote: {
        url: 'typeahead.php?programme&type=1&school_name=',
        replace: function () {
            var q = 'typeahead.php?programme&type=1&school_name=';
            if ($('#school').val()) {
                q += encodeURIComponent($('#school').val());
            }
            return q;
        }
    },
    cache: false,
    limit: 10
});

Based on this threads answer: Bootstrap 3 typeahead.js - remote url attributes

See function "replace" in the typeahead.js docs


There is actually a slight refinement of Mattias' answer available in the newer Bloodhound js, which reduces duplication and opportunity for error:

$('#programme').typeahead({
    remote: {
        url: 'typeahead.php?programme&type=1&school_name=',
        replace: function (url, query) {
            if ($('#school').val()) {
                url += encodeURIComponent($('#school').val());
            }
            return url;
        }
    },
    cache: false,
    limit: 10
});