Multiple columns autocomplete textbox using WebAPI , CSS and javascipt with out using JQuery autocomplete textbox plugins.

Introduction:
This article explain you to create autocomplete text box using WebAPI , CSS and Javascript .
Description:
Below C# code is used to create a multi column autocomplete text box using WebAPI , CSS and javascipt with out using JQuery autocomplete textbox plugins. Generally to create a autocompelte
text box we use JQuery autocomplete plugins , but with JQuery autocompelte textbox plugins
it is not possible to create a multiple columns autocomplete textbox.
To implement this we need to write the code like as shown below

SQL Server Code:-

Create table as follows :
emploeetable

HTML Java Script CSS:

  <script type="text/javascript">
        var pivotPoint;
        var currentRequest;
        var searchdata;

        var y = -1;
        function getitems() {
            currentRequest = null;
            var searchKey = $('#TxtSearch').val();
            if (searchKey != '' && searchKey.length > 2) {
                currentRequest = $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "../api/Search/SearchEmployees?strSearchkey=" + searchKey + "",
                    dataType: "json",
                    beforeSend: function () {
                        if (currentRequest != null) {
                            currentRequest.abort()
                        }
                    },
                    success: function (data) {
                        searchdata = data;
                        searchResult(data);
                    },
                    error: function (result) {
                        alert("Error");
                    }
                });

            }
            else {
                document.getElementById('dvSearchResult').style.display = "none";
            }

        }
        function searchResult(data) {
            var pivotElement = document.getElementById('TxtSearch');
            var pos = $("#TxtSearch").position();
            var resultitemHtml;

            if (data.length > 0) {

                resultitemHtml = '<table id=\"tblitemslist\">';
                for (var i = 0; i < data.length; i++) {
                    resultitemHtml += '<tr    style=\"cursor: pointer;font: 14px Cambria;width:100%;border:solid 0px red;\">';
                    resultitemHtml += '<td style=\"text-align:left;border:solid 1px #cccccc;\">' + data[i].Name + '</td><td style=\"width:77px;border:solid 1px #cccccc;\">' + data[i].Gender + '</td><td style=\"width:60px;border:solid 1px #cccccc;\">' + data[i].DeptId + '</td><td style=\"width:67px;border:solid 1px #cccccc;\">' + data[i].Salary + '</td></tr>';
                }
                resultitemHtml += '</table>';
                document.getElementById('dvSearchResult').innerHTML = resultitemHtml;
                document.getElementById('dvSearchResult').style.display = "block";
                document.getElementById('dvSearchResult').style.height = '200px';

            }
            else {
                document.getElementById('dvSearchResult').innerHTML = '<span style=\"font: 16px Cambria;color:#000;\">No Search Found</span>';
                document.getElementById('dvSearchResult').style.display = "block";
                document.getElementById('dvSearchResult').style.textAlign = 'center';
                document.getElementById('dvSearchResult').style.height = '20px';
            }
            document.getElementById('dvSearchResult').style.width = $('#TxtSearch').width() + 10 + 'px';
            document.getElementById('dvSearchResult').style.top = (pos.top + 25) + 'px';
            document.getElementById('dvSearchResult').style.left = (pos.left) - 5 + 'px';
            document.getElementById('dvSearchResult').scrollTop = 0;
        }
        function keynavigation(e) {
            var key = document.all ? window.event.keyCode : e.which;
            var $listlength = $("#tblitemslist > tbody > tr").length
            var $listItems = $('#tblitemslist tr');
            $selected = $listItems.filter('.selected');
            var $current;

            switch (key) {


                case 38://UP KEY

                    $listItems.removeClass('selected');
                    if (!$selected.length || $selected.is(':first-child')) {
                        $current = $listItems.last();
                        y = $listlength - 1;

                    }
                    else {
                        $current = $selected.prev();
                        y--;
                    }
                    $current.addClass('selected');

                    break;
                case 40://DOWN KEY
                    $listItems.removeClass('selected');
                    if (!$selected.length || $selected.is(':last-child')) {
                        $current = $listItems.eq(0);
                        y = 0;
                    }
                    else {
                        $current = $selected.next();
                        y++;

                    }
                    $current.addClass('selected');

                    break;
                default:
                    getitems();
                    break;
            }


        }




    </script>

CSS

 <style type="text/css">
        .DynDivBox {
            display: none;
            border: solid 1px #999;
            background-color: rgba(255, 255, 255, 0.80);
            position: absolute;
            text-align: left;
            vertical-align: top;
            border-radius: 2px;
            -moz-border-radius: 2px;
        }

            .DynDivBox table {
                width: 100%;
                text-align: center;
            }

                .DynDivBox table td {
                    padding: 5px;
                    cursor: pointer;
                }

        .selected {
            background-color: #a5b6c4;
        }
    </style>

HTML

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>AutoComplete Text Box with multiple columns with css and javascript</title>

    <script src="../scripts-common/jquery-2.1.4.js"></script>
 


</head>
<body>

    <div style=" margin: auto; width: 65%; margin: auto; border: solid 1px #000;">
        <b>Auto Complete Text Box with multiple columns using css and java script , with out using Jquery Autocomplete plugins.</b>
        <div style="text-align: center; margin-top: 10px; height: 300px;">
            <b>Search :</b>
            <input type="text" id="TxtSearch" placeholder="Search Items" runat="server" onkeyup="keynavigation(event)" clientidmode="static" style="width: 500px;" />
            <div id="dvSearchResult" class="DynDivBox" style="height: 90px; overflow: auto; border: 0px solid #000;"></div>

        </div>

        <div style="text-align:center;">
            <b>© 2016 www.logicspark.in by Muhammad Asif</b>
        </div>
    </div>

</body>
</html>

C# Web API Controller

using AngularJSCURD.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace AngularJSCURD.Controllers
{
    public class SearchController : ApiController
    {
        string strConnectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
        string strSQLQuery = "";


        [HttpPost]
        public List<Employee> SearchEmployees(string strSearchkey)
        {
            IDataReader objIDataReader;

            strSQLQuery = "SELECT TOP 5 * FROM tblEmployees WHERE Name LIKE '%" + strSearchkey + "%'";
            List<Employee> objEmployeeList = new List<Employee>();
            using (SqlConnection con = new SqlConnection(strConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = strSQLQuery;
                    cmd.Connection = con;
                    con.Open();
                    objIDataReader = cmd.ExecuteReader();
                    while (objIDataReader.Read())
                    {
                        Employee objEmployee = new Employee();
                        objEmployee.Id = Convert.ToInt32(objIDataReader["Id"]);
                        objEmployee.Name = objIDataReader["Name"].ToString();
                        objEmployee.Gender = objIDataReader["Gender"].ToString();
                        objEmployee.DeptId = Convert.ToInt32(objIDataReader["DeptId"]);
                        objEmployee.Salary = Convert.ToInt32(objIDataReader["Salary"]);
                        objEmployeeList.Add(objEmployee);
                    }

                }
            }
            return objEmployeeList;
        }

     
    }
}

DEMO

autocompletetextbox

No comments:

Post a Comment

Blogger Tips and TricksLatest Tips And TricksBlogger Tricks