In this article I will show you how to use datalist to create jQuery autocomplete multiple values from database. You should make an Ajax call to server method GetCompanyList() and fetch company name and city from the customer table and return as JavaScript object bind into datalist element with values and label.
Here I am using Northwind database. You can download it from following link.
Open Microsoft sql management studio and right click on the database and attach it.
Step 1: Create an ado.net entity data model using table Customer and generate entity for that.
Step 2: Right click on the "Controllers" folder and add "Home" controller. Copy and paste the following code.
public ActionResult Index()
{
return View();
}
public JsonResult GetCompanyList(string criteria)
{
models db = new models();
var query = (from c in db.Customers
where c.CompanyName.Contains(criteria)
orderby c.CompanyName ascending
select new { c.CompanyName, c.City }).Distinct();
return Json(query.ToList(), JsonRequestBehavior.AllowGet);
}
Step 3: Right click on the HomeControllers and create an index view. Copy and paste the following code.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#companyName").on("input", function () {
var options = {};
options.url = "/autocomplete/getcompanylist";
options.type = "GET";
options.data = { "criteria": $("#companyName").val() };
options.dataType = "json";
options.success = function (data) {
$("#companyList").empty();
for (var i = 0; i < data.length; i++) {
$("#companyList").append("<option value='" +
data[i].CompanyName + "' label=" + data[i].City + "></option>");
}
};
$.ajax(options);
});
});
</script>
<div style="border: 1px solid #DED8D8; width: 450px; height: 300px;padding-left:15px; font-family: Arial;">
<h1>Datalist autocomplete from database in jQuery</h1>
<input id="companyName" list="companyList" />
<datalist id="companyList"></datalist>
</div>
html5 autocomplete datalist from database in jQuery
Post your comments / questions
Recent Article
- How to create custom 404 error page in Django?
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
Related Article