Reputation: 98
I'm just trying something out, as an experiment, with the jQuery autocomplete widget.
I used this as an example: Autocomplete | APi Data
But when i try it, it's not filtering the results. it only shows all results when i type something and then 'backspace-it-all'
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "https://nyros-ecommerce.myshopify.com/products.json",
dataType: "json",
dataFilter: function (data) { return data; },
success: function( data ) {
console.log(data)
response( $.map( data.products, function( result ) {
return {
value: result.handle,
imgsrc: result.images[0].src
}
}));
}
});
},
minLength: 1,
select : function(event, ui) {
event.preventDefault();
window.location.href = "/products/"+ui.item.value;
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
console.log(item.value)
return $( "<li></li>" )
.data( "item.ui-autocomplete", item.value )
.append( "<a>" + "<img style='width:50px;height:55px' src='" + item.imgsrc + "' /> " + item.label+ "</a>" )
.appendTo( ul );
};
});
</script>
<div class="ui">
<label for="name">producst search: </label>
<input id="name">
</div>
Upvotes: 0
Views: 585
Reputation: 1571
The only issue with your code is, you are fetching data in function but not filtering the data.
You just need to filter your data using the following line. Here final_data
is nothing but your resulted output.
response($.ui.autocomplete.filter(final_data, request.term));
Try below code.
$(function() {
$( "#name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "https://nyros-ecommerce.myshopify.com/products.json",
dataType: "json",
dataFilter: function (data) { return data; },
success: function( data ) {
var final_data =( $.map( data.products, function( result ) {
return {
value: result.handle,
imgsrc: result.images[0].src
}
}));
response($.ui.autocomplete.filter(final_data, request.term));
}
});
},
minLength: 1,
select : function(event, ui) {
event.preventDefault();
window.location.href = "/products/"+ui.item.value;
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.ui-autocomplete", item.value )
.append( "<a>" + "<img style='width:50px;height:55px' src='" + item.imgsrc + "' /> " + item.label+ "</a>" )
.appendTo( ul );
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<div class="ui">
<label for="name">producst search: </label>
<input id="name">
</div>
Upvotes: 3