Skip to content

Instantly share code, notes, and snippets.

@cfjedimaster
Created June 14, 2012 12:21
Show Gist options
  • Save cfjedimaster/2929966 to your computer and use it in GitHub Desktop.
Save cfjedimaster/2929966 to your computer and use it in GitHub Desktop.
<!doctype html>
<html>
<head>
<title>Example 1</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#search").on("input", function(e) {
var val = $(this).val();
if(val === "") return;
//You could use this to limit results
//if(val.length < 3) return;
console.log(val);
$.get("artservice.cfc?method=getart&returnformat=json", {term:val}, function(res) {
var dataList = $("#searchresults");
dataList.empty();
if(res.DATA.length) {
for(var i=0, len=res.DATA.length; i<len; i++) {
var opt = $("<option></option>").attr("value", res.DATA[i][0]);
dataList.append(opt);
}
}
},"json");
});
})
</script>
</head>
<body>
<p>
<input type="text" name="search" id="search" placeholder="Type Something" list="searchresults" autocomplete="off">
<datalist id="searchresults"></datalist>
</p>
</body>
</html>
@wingwan
Copy link

wingwan commented Jun 19, 2013

<!doctype html>

<title>Example 1</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> $(document).ready(function() { $("#search").on("keyup", function(e) { var val = $(this).val(); if(val === "") return; //You could use this to limit results //if(val.length < 3) return; console.log(val); $.ajax({ type : "get", async:false, url : "http://suggestion.baidu.com/su?wd=" + val, dataType : "jsonp", jsonp: "cb", success : function(json){ var dataList = $("#searchresults"); dataList.empty(); if(json.s && json.s.length) { for(var i=0, len=json.s.length; i").attr("value", json.s[i]); dataList.append(opt); } } }, error:function(){ alert('fail'); } }); }); }) </script>

#

Hi, I have tried your code, and met some problems. When I enter a letter, the options have been appended to the datalist element, but the list sometimes shows ,sometimes not. And it shows the list related to the word I input last time.

@wingwan
Copy link

wingwan commented Jun 19, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment