Autocomplete Textbox Using Jquery/JSON from Database

JSONIn web page designing  autocomplete property of textbox is widely used for making the site user friendly and interactive , so in this article we will understand the simple method for autocompletion of textbox using Jquery.

First we will see a simple example for this then in next step I will show you how you can fetch the data from the database using JSON

HTML Code

<html>
<head>

<!-- Load jQuery, jQuery UI and jQuery ui styles from jQuery website -->
<<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>

var data = [
"Delhi",
"Mumbai",
"Indore",
"Dehradun",
"Assam"];
$(document).ready(
function () {
 $("#City").autocomplete({
source: data,
 autoFocus: true,
});
}
);
</script>
</head>

<body>

<label for="City">City <input type="text" name="CityNames" id="City" /></label>
</body>

</html>

After running the code in browser you will see the page having the city textbox which will be autocompleted when you start typing. AutoFillNow if you want your city name fetched from database  the simple way out for doing that will be using JSON data First write the method for getting the JSON data from database , I will show you a simple example for that ,

JSON Method –

public JsonResult AutoCompleteCityList(string term)
 {
 JsonResult result = new JsonResult();
var vStateList = "write here your database connection code for gettig city name List ";
var namelist = vStateList.Where(n => n.CityName.ToLower().StartsWith(term.ToLower()));
 return Json(namelist, JsonRequestBehavior.AllowGet);

 }
    



<script type="text/javascript">,

 

 $(document).ready(function () {

 $("#City").autocomplete({

minlength:3,

 source: function (request, response) {

$.ajax({

 url: "/AutoCompleteCityList",

 type: "POST",

 dataType: "json",

data: { term: request.term },

 success: function (data) {

 response($.map(data, function (item) {

return {

label: item.CityId,

value: item.CityName

};

}));

},

 select: function (event, ui) {

event.preventDefault();

 $('#City').val(ui.item.val);

},

 focus: function (event, ui) {

event.preventDefault();

 $(this).text(ui.item.label);

},

messages: {

 noResults: "", results: "",

}

});

}

});

})

</script>

 

Just use this code and you will be easily able to use the autocomplete property in your  site .
Happy Coding!!

 

Leave a Reply

Your email address will not be published. Required fields are marked *