Published on: 04 December, 2017

How to create autocomplete text box using pure Javascript, CSS3 and Web API C# ASP.Net

Posted by andy | 73 views 0 likes 0 favourites 0 comments
Tumblr Digg Google Plus

In this tutorial, you will learn how to create a simple autocomplete search using pure javascript and CSS3. No JQuery plugin is required for this tutorial.

Let's get started with the interface of our screen page. Our example screen page will have a text box for you to enter the country keyword and a summary table that will display the selected country id represents the database id key of the country object. We will use Web API C#.Net to get the list of countries based on keyword input.

In this example, we will return top 10 match records with minimum 2 characters enter required for the auto-complete query. Note: This tutorial will focus more on the front end part only. I will include a quick simple Web API function to return a list of Country data as an example only.

Here is the code of the screen page contains a text box for keyword search and a summary table to display the selected country id.

<p>Search: <input type="text" id="txtKeyword"/></p>
<table cellpadding="5" cellspacing="1" border="1">
	<tr>
		<td>Country ID:</td>
		<td><span id="selected-countryid">0</span></td>
	</tr>
</table>

Let make a list of required items we need to build the whole solution.

  1. We need to add an event listener to our keyword text box by adding a key up event when the page is fully loaded.
  2. We then check if a keyword box div has already been created in search box div. If it has not been created, we then append the div keyword box inside the search box div.
  3. We set the position of the parent node of the text box to relative position by adding a relative class.
  4. We add a class to our keyword list box with position absolute against the parent node which is the search box div and adjust the position of the keyword box we want to display. This can be done via css to sure our keyword box is positioned nicely under the keyword text box.
  5. The next part is to perform a fetch query. We will pass an argument of a keyword string to Web API URL. It will then return a list of countries match with our entered keyword. Before we pass the query to Web API, we have to make sure the keyword must contain a minimum of 2 characters. As the Web API actually return a list of possible match countries and we want to return only 10 records at max, when performing a for loop, we need to make sure to only return a maximum of 10 records. As this is an example only, parameters used in Web API is only accepting keyword string. For real situation, we may want to add extra option like to accept a number of maximum records you want to return.
  6. Once we get the return countries records, we then append it to our keyword box list. If there is no record found or doesn't meet the minimum requirement of characters we then clear the keyword box.

Here is the full code of the javascript. I have included the comment so you can see what the code does.

<script>

	//constant variables, you can change the minimum characters or maximum records return.
	const noOfChars = 2;
	const maxList = 10;
	
	//variable to hold the text box keyword html object
	var keywordTextBox = {};
	
	//an array to hold the return list of countries
	var keywordList = {};
	
	//initiation function to add the event listener to the keyword text box
	initKeywordSearch = function(){
		//add the keyup listener event to textbox
		keywordTextBox = document.getElementById("txtKeyword");
		keywordTextBox.addEventListener("keyup", function(){
			//clear data
			document.getElementById("selected-countryid").innerHTML = "0";
			
			//get the search text keyword value and pass it into showKeywordList function.
			showKeywordList(keywordTextBox.value);
		});
		
		document.body.addEventListener("click", function(){
			if(keywordList != null){
				keywordList.style.display = "none";
			}
		});
	}
	
	//function to show the keyword box list.
	showKeywordList = function(textValue){
		// we try to get a keyword box list, and see if it is already exists.
		keywordList = document.getElementById("keyword-list");
		
		//if it is not exist then we create the object
		if(keywordList == null){
			//create a keyword box (div html format)
			var divKeywordBox = document.createElement("div");
			//add the id key for easy search
			divKeywordBox.id = "keyword-list";
			
			//we append the div into the search box div
			document.getElementById("search-box").appendChild(divKeywordBox);
			
			//get the keyword box list object and set a class relative to the object
			keywordList = document.getElementById("keyword-list");
			keywordList.parentNode.classList.add("relative");
			
		}
		
		//set the display by default to none (not visible)
		keywordList.style.display = "none";
		
		//only process if the value is keyword entered is not empty
		if(textValue != ""){
			//if the minimum characters is met then process ahead
			if(textValue.length >= noOfChars){
				//perform a json fetch data
				var counterFound = 0;
				var url = "http://bytutorial.com/API/ExampleJSON/QueryCountry?keyword=" + keywordTextBox.value;
				fetch(url, {
					method: 'post',
					headers: {'Content-Type':'application/json; charset=utf-8'}
				}).then(function(response) {
					return response.json();
				}).then(function(example_data){
					//clear the keyword box content
					keywordList.innerHTML = "";
					
					//this array will be used to hold new data
					var newList = [];
					for(var i = 0; i < example_data.length; i++){
						newList.push(example_data[i]);
						counterFound++;
						
						//perform a break if has reaced max list needed.
						if(counterFound >= maxList) {break;}
					}
					
					//only display if the new list has more than 1 record.
					if(newList.length > 0){
						//show the keyword box
						keywordList.style.display = "block";
						
						//populate the country item row inside the keyword box and add an on click event to show the id of the country
						newList.forEach(function(item, index){
							keywordList.insertAdjacentHTML("beforeend", "<div data-index='" + item.CountryID + "' data-text='" + item.CountryName + "' class='keyword-item' onclick='showSelected(this)'>" + item.CountryName + "</div>");
						});
					}
				});
			}
		}
	}
	
	//function to show country summary
	showSelected = function(obj){
		//display the country id in the summary table
		document.getElementById("selected-countryid").innerHTML = obj.getAttribute("data-index");
		
		//set the keyword text box to country name
		keywordTextBox.value = obj.getAttribute("data-text");
		
		//hide the keyword box
		keywordList.style.display = "none";
	}
	
	//initiate the auto complete keyword search
	window.onload = initKeywordSearch;
</script>

Here is the full code of the css stylesheet.

<style>
	/* set position to relative, this is for the keyword textbox parent */
	#search-box{
		position:relative;
		padding:10px;
	}
	
	/* style the keyword box contains list of keyword items */
	#keyword-list{
		position:absolute;
		width:250px;
		border:solid 1px #ccc;
		box-shadow: 4px 6px 11px 0px rgba(87,87,84,0.8);
		z-index:9999;
		background:#fff;
        top:42px;
        left:62px;
	}
	
	/* style the keyword item row */
	.keyword-item{
		padding:5px;
		border-bottom:solid 1px #f2f7f9;
		cursor:pointer;
	}
	
	/* When hovering the keyword item, change the background color */
	.keyword-item:hover{
		background:#f1fafd;
	}
</style>

Here is the sample of Web API C# ASP.Net that will return a list of countries records based on a query keyword. Note: in this example, I create a static list of records for test purpose only. You may want to modify the code accordingly if you want to access to a database.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Security;

namespace bytutorial.com.WebAPI
{
    public class ExampleJSONController : ApiController {
        [HttpPost]
        public HttpResponseMessage QueryCountry(string keyword) {
            List countryList = new List();
            #region country data
            countryList.Add(new ExampleCountryInfo() { CountryID = 3, CountryName = "Afghanistan" });
            countryList.Add(new ExampleCountryInfo() { CountryID = 6, CountryName = "Albania" });
            countryList.Add(new ExampleCountryInfo() { CountryID = 58, CountryName = "Algeria" });
            countryList.Add(new ExampleCountryInfo() { CountryID = 12, CountryName = "American Samoa" });
            countryList.Add(new ExampleCountryInfo() { CountryID = 1, CountryName = "Andorra" });
            /* ... and so on ....*/
            countryList.Add(new ExampleCountryInfo() { CountryID = 238, CountryName = "Zimbabwe" });
            #endregion

            countryList = countryList.Where(x => x.CountryName.ToLower().Contains(keyword.ToLower().Trim())).ToList();
            return Request.CreateResponse(HttpStatusCode.OK, countryList);
        }
    }

    public class ExampleCountryInfo{
        public int CountryID { get; set; }
        public string CountryName { get; set; }
    }
}

Autocomplete Demo using pure Javascript, CSS3 and Web API C# ASP.Net

You can see the actual demo of the autocomplete below.

Country ID: 0

Feel free to post your comment below, if you have any question regarding with this tutorial.

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.
Share your article with us and add your own google adsense account to earn extra money. Plus, you can promote a link back to your site.
Related Articles
Published on: 20 June, 2016
Google Analytics is one of the best free analytics site tracker. It gives you an idea the statistic of your visitors like the country they come from, the URL or keyword they search to go to your site or even the demographic or ages of your visitors. If you are a developer, you definitely do not want to track any data when you are in development phase. In this tutorial, you will learn how to disable google analytics for local development by using a javascript code if condition.
Published on: 13 May, 2016
To convert a number value into money format in Javascript can be done easily using Javascript. Firstly you will need to use the built in toFixed function that will return a number value into two decimal point and then using a regular expression to reformat the value.
Published on: 16 March, 2016
If you try to search this particular topic in Google Search, you will come up with a list of different solutions. Most of them will use the document or body height to compare if there is a difference, we assume there will be a scroll bar. Unfortunately it doesn't work well, most of them it will return the same height.
Related Tutorials