Skip to content

Instantly share code, notes, and snippets.

@John-Henrique
Last active June 6, 2016 04:13
Show Gist options
  • Save John-Henrique/6b23cb89aa75899e5022 to your computer and use it in GitHub Desktop.
Save John-Henrique/6b23cb89aa75899e5022 to your computer and use it in GitHub Desktop.
<input type="text" id="search" list="search-response" placeholder="Search cars...">
<datalist id="search-response">
    <option value="Acura">
    <option value="Audi">
    <option value="BMW">
    <option value="Cadillac">
    <option value="Chrysler">
    <option value="Dodge">
    <option value="Ferrari">
    <option value="Ford">
    <option value="GMC">
    <option value="Honda">
    <option value="Hyundai">
    <option value="Infiniti">
    <option value="Jeep">
    <option value="Kia">
    <option value="Lexus">
    <option value="Mini">
    <option value="Nissan">
    <option value="Porsche">
    <option value="Subaru">
    <option value="Toyota">
    <option value="Volkswagen">
    <option value="Volvo">
</datalist>
<script>
// Every each keypress
$( document ).on( 'keypress', '#search', function(){
// only if user has typed 3 digits or more
if( $( this ).val().length >= 3 ){
// request ajax call
$.ajax({
url: "http://YOURWEBSITE.COM/api/v1/search", // URL example
type: "GET"
}).done( function( response ){
// only to debug, isn't necessary
console.log( response );
html = ""; // initialize html var
$.each( response, function( index, key ){
/*
imagining that response is an Array like
title, title, title
*/
html += "<option value=\""+ key.title +"\">"; // append option
});
// write HTML option in datalist
$( "#search-response" ).html( html );
}).fail( function( x, h , r ){
// case fail
console.log( 'error' );
});
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment