Reputation: 1059
I'm struggling for 3-4 hours with Bootstrap's typeahead
that I downloaded from https://github.com/twitter/typeahead.js/
I'm trying to add a click function with typeahead's suggestion to change page with javascript's window.location.href
.
My typeahaed works well with json values
// Typeahead
$("#search-product").typeahead({
ajax: {
url: "_inc/search-json.php?product=",
timeout: 500,
displayField: "product_name",
triggerLength: 3,
method: "get",
preDispatch: function (query) {
return {
search: query
}
},
}
});
In suggestion ul
suggestions coming with 2 values; 1)Product Name, 2) Product Id. Sample html structure;
<ul class="typeahead dropdown-menu">
<li data-value="166" class=""><a href="#"><strong>TK03</strong>0</a></li>
<li data-value="167"><a href="#"><strong>TK03</strong>1</a></li>
</ul>
and I try to add click function to li
's redirect user to product detail page with jquery
code;
var productId = $('.typeahead li').data("value");
$(".typeahead").on( "click", "li", function() {
window.location.href = "/product-details.php?i=" + productId;
});
But it's always redirecting to: product-details.php?i=undefined
What is wrong with my code, what am I missing?
Upvotes: 2
Views: 2336
Reputation: 4757
var productId = $('.typeahead li').data("value"); // Doesnt make any sense outside the click callback. Instead write it within the callback like shown below.
You need to fetch the product Id it like this inside your click
callback:
$(".typeahead").on( "click", "li", function() {
var productId = $(this).data("value"); // $(this) refers to the clicked li
window.location.href = "/product-details.php?i=" + productId;
});
Upvotes: 2