JSFiddle - React, Tailwind, and code Playground

by Jam Cow

HTML

<script src="http://twitter.github.com/typeahead.js/releases/latest/typeahead.bundle.min.js"></script>
<input type="text" id="searchCategory" class="typeahead" value="all">
<input type="text" id="searchProducts" class="typeahead" value="">

JavaScript

// If I set the value beforehand, the query/ajax works successfully and I get results as intended, eg value="green"
var searchInput = $('#searchProducts').val();

// This is a fake dropdown menu that updates the category input value to "all" or "gardening"
var searchCategoryInput = $('#searchCategory').val();


var products = new Bloodhound({

    name: 'productlist',
    remote: {
        url: "/products/productsearchsuggestions",
        ajax: {

            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({
                partialSearchString: searchInput,
                category: searchCategoryInput
            }),
            success: function (data) {
                console.log("We have data:");
                console.log(data);
            }
        }
    },
    datumTokenizer: function (d) {
        return Bloodhound.tokenizers.whitespace(d.Value)
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace
});

products.clear();
products.initialize(true);

$('#searchProducts').typeahead(null, {
    name: 'products',
    displayKey: 'Value',
    source: products.ttAdapter()
})
.on('typeahead:opened', onOpened)
.on('typeahead:autocompleted', onAutocompleted)
.on('typeahead:selected', onSelected);


function onOpened($e) {
    console.log('opened');
}

function onAutocompleted($e, datum) {
    console.log('autocompleted');
    console.log(datum);
}

function onSelected($e, datum) {
    console.log('selected');
    console.log(datum);
}