Select function of Autocomplete textbox using jQuery

In autocomplete textbox feature, we can also add our own functionality when any text is selected from autocomplete drop-down using select function.

Let us say, we can display one alert message when a text is selected from autocomplete textbox.

Following is the code snippet for including select function in autocomplete feature:

		$("#suggestions").autocomplete({
			source : availableTags,
			select : function(event, ui) {
				alert ("You have selected : " + ui.item.value);
				$("#suggestions").val(ui.item.value);
				return false;
			},

			delay : 0
		});

The entire HTML file will look like below:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Autocomplete in jQuery</title>

<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/base/jquery-ui.css">
<script type='text/javascript' src='http://code.jquery.com/jquery-1.5.2.js'></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js"></script>

<style>
.ui-widget {
	font-size: 12px;
}

.frame {
	left: 150px;
	top: 150px;
	width: 500px;
	border: #e6e6e6 solid 1px;
	position: absolute;
	align: center;
	padding: 10px;
}
</style>

<script type="text/javascript">

	$(function() {
		$.extend($.ui.autocomplete.prototype, {
			_renderItem : function(ul, item) {
				var term = this.element.val(), html = item.label.replace(term,
						"<b>" + term + "</b>");
				return $("<li></li>").data("item.autocomplete", item).append(
						$("<a></a>").html(html)).appendTo(ul);
			}
		});

		var availableTags = [ "C", "C++", "Java", "PHP", "Python", "Cobol",
				".NET", "DB2", "Oracle", "MySQL", "MS SQL Server", "Cassandra" ];

		$("#suggestions").autocomplete({
			source : availableTags,
			select : function(event, ui) {
				alert ("You have selected : " + ui.item.value);
				$("#suggestions").val(ui.item.value);
				return false;
			},

			delay : 0
		});
	});
</script>

</head>
<body>

	<div>
		<div>
			<input id="suggestions">
		</div>
	</div>

</body>
</html>

Share This Post

Related Articles

One Response to “Select function of Autocomplete textbox using jQuery”

  1. how to delete google plus account on ipad says:

    It’s very straightforward to find out any topic on
    net as compared to books, as I found this article
    at this site.

Leave a Reply

© 2017 Techy Diary. All rights reserved.
Powered by Charvi Groups