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 get domain name information from a Domain using Python
- ModulenotFoundError: no module named 'debug_toolbar' -SOLUTION
- How to create superuser in django project hosted in cPanel without terminal
- CSS & images not loading in django admin | cpanel without terminal
- Could not build wheels for mysqlclient, which is required to install pyproject.toml-based projects
- How to sell domain name on Godaddy (2023)
- TemplateSyntaxError at / Could not parse the remainder: ' + 1' from 'forloop.counter0 + 1'
- urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'OpenSSL 1.0
Related Article