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 add two numbers in Android Studio? | Source Code
- FindViewByID returns null in android studio -SOLVED
- Saving changes is not permitted in SQL SERVER - [SOLVED]
- Restore of database failed. File cannot be restored over the existing. -[SOLVED]
- One or more projects in the solution were not loaded correctly in Visual Studio 2019 | FIXED
- How to find Laptop's Battery Health?
- SOLVED-Related Field got invalid lookup: icontains error in Django
- How to enable Search Feature in Django admin?
Related Article