In this short article I will provide an informative tip for jQuery developers i.e. how to clear jQuery Autocomplete TextBox after item is selected from jQuery Autocomplete Items.
Below is an HTML Page with a jQuery Autocomplete TextBox.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
type="text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
rel="Stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$("#autocomplete").autocomplete({
source: ["c",
"c++",
"java",
"php",
"coldfusion",
"javascript",
"asp",
"ruby",
"asp.net",
"sql server"],
select: function (e, u) {
$("#selection").html(u.item.value);
$(this).val("");
return false;
}
});
});
</script>
</head>
<body>
<input type="text" id="autocomplete" />
<br />
<span id = "selection"></span>
</body>
</html>
Explanation:
I have defined the select event handler for the jQuery Autocomplete within which I have first cleared the TextBox by accessing it using the $(this) selector and then to stop further execution of the event I have added return false; statement.
Before clearing the TextBox I am storing the selected jQuery Autocomplete item in HTML SPAN with ID selection for display purpose, you can make use of Hidden Field too based on your requirement.
Demo
Downloads