How to set filter functionality in dropdown using textbox using JavaScript and CSS

In this article, we have shown filter Functionality in drop down list according to textbox or normally .We use this code to make new feature in autocomplete in easiest way and make also stylish.Many times we have seen this code on quiktr, Olx and other classifieds web site . 


Source Code:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="dropdownlistwithfilter.aspx.cs" Inherits="dropdownlistwithfilter" %>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href='http://fonts.googleapis.com/css?family=Roboto+Condensed' rel='stylesheet' type='text/css'>
    <script src="http://code.jquery.com/jquery-2.2.1.min.js"></script>
    <link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
    <script>
        ; (function ($) {
            "use strict";
            var TinySelect = {
                init: function ($el, options) {
                    $el.data("tinySelectObj", this);
                    this.config = $.extend({
                        showSearch: true,
                        txtLoading: "Loading...",
                        txtAjaxFailure: "Error...",
                        dataUrl: null,
                        dataParser: null
                    }, options);

                    this.state = {
                        container: null,
                        selectBox: null,
                        itemContainer: null,
                        searchContainer: null,
                        searchBox: null,
                        $el: null,
                        open: false,
                        ajaxPending: false,
                        selectedValue: -1,
                        originalItemData: [],
                        filteredItemData: []
                    };
                    this.readSelect($el);
                    this.createSelect($el);
                },

                createSelect: function ($el) {
                    // Create container for select, search and options
                    this.state.container = $("<div></div>").
                        addClass("tinyselect").
                        css({ width: $el.css("width") });

                    // Create the select element
                    this.state.selectBox = $("<div></div>").
                        addClass("selectbox").
                        on("click", { self: this }, this.onSelectBoxClicked);

                    this.state.container.append(this.state.selectBox);

                    // Create container to hold search and results
                    this.state.dropdown = $("<div></div>").
                        addClass("dropdown").
                        hide();

                    this.state.container.append(this.state.dropdown);

                    // Add search as first element
                    if (this.config.showSearch)
                        this.createSearch(this.state.dropdown);

                    // Create ul to hold items            
                    this.state.itemContainer = $("<ul></ul>").
                        addClass("itemcontainer");
                    this.state.dropdown.append(this.state.itemContainer);

                    //
                    this.createItems();

                    // Hide original select element and add new component to below
                    $el.hide().after(this.state.container);
                    this.state.$el = $el;

                    // Hide select content when clicked elsewhere in the document
                    $(document).on("click", { self: this }, this.onDocumentClicked);
                },

                createItems: function (selected) {
                    var l1, opt;

                    // Remove all
                    this.state.itemContainer.empty();

                    //
                    for (l1 = 0; l1 < this.state.filteredItemData.length; l1++) {
                        opt = this.state.filteredItemData[l1];

                        var newLi = $("<li></li>").
                            text(opt.text).
                            addClass("item").
                            attr("data-value", opt.val);

                        if (opt.val == this.state.selectedValue) {
                            this.state.selectBox.html(opt.text);
                            newLi.addClass("selected");
                        }

                        newLi.on("click", { self: this }, this.onSelectLiClicked);

                        this.state.itemContainer.append(newLi);
                    }
                },

                createSearch: function ($el) {
                    this.state.searchContainer = $("<div></div>").
                        addClass("searchcontainer");
                    this.state.searchBox = $("<input type='text'></input>").
                        addClass("searchbox").
                        on("click", function (e) { e.stopPropagation(); }).
                        on("keyup", { self: this }, this.onSearchKeyPress);

                    this.state.searchContainer.append($("<span class='searchicon'></span>"));
                    this.state.searchContainer.append(this.state.searchBox);
                    this.state.dropdown.append(this.state.searchContainer);
                },
                readSelect: function ($el) {
                    var self = this;

                    $el.find("option").each(function (index) {
                        var opt = $(this);
                        self.state.originalItemData.push({ val: opt.val(), text: opt.text() });
                    });

                    this.state.filteredItemData = this.state.originalItemData;
                    this.state.selectedValue = $el.val();
                },

                setAjaxIndicator: function (failure) {
                    this.state.ajaxPending = true;
                    this.state.itemContainer.empty();

                    if (this.state.searchContainer !== null)
                        this.state.searchContainer.hide();

                    var newLi = $("<li></li>");
                    if (!failure) {
                        newLi.text(this.config.txtLoading).
                        addClass("loadindicator");
                    } else {
                        newLi.text(this.config.txtAjaxFailure).
                        addClass("loaderrorindicator");
                    }

                    this.state.itemContainer.append(newLi);
                },
                onDocumentClicked: function (e) {
                    var self = e.data.self;

                    if (self.state.open)
                        self.onSelectBoxClicked(e);
                },
                onSearchKeyPress: function (e) {
                    var self = e.data.self,
                        sval = $(e.currentTarget).val();
                    if (sval.length === 0) {
                        self.state.filteredItemData = self.state.originalItemData;
                    } else {
                        self.state.filteredItemData = self.state.originalItemData.filter(function (item) {
                            return item.text.toLowerCase().indexOf(sval) >= 0 ? true : false;
                        });
                    }
                    self.createItems();
                },
                onSelectBoxClicked: function (e) {
                    var self = e.data.self;
                    // Do nothing, if currently animating
                    if (self.state.dropdown.is(":animated"))
                        return;
                    // Close selectBox
                    if (self.state.open) {
                        self.state.open = false;
                        self.state.selectBox.removeClass("open");
                        self.state.dropdown.slideUp(100);
                        return;
                    }
                    // Open selectbox
                    if (self.config.dataUrl !== null) {
                        self.setAjaxIndicator(false);
                        $.ajax({
                            url: self.config.dataUrl,
                            dataType: "json",
                            type: "GET"
                        }).done(function (data) { self.onAjaxLoadSuccess(self, data); }).
                            fail(function (data) { self.onAjaxLoadError(self, data); });
                    }
                    self.state.open = true;
                    self.state.selectBox.addClass("open");
                    self.state.dropdown.slideDown(100);
                },
                onAjaxLoadSuccess: function (self, data) {
                    self.state.ajaxPending = false;
                    if (self.config.dataParser !== null) {
                        data = self.config.dataParser(data, self.state.selectedValue);
                    }
                    self.state.$el.empty();
                    data.forEach(function (v) {
                        if (v.selected)
                            self.state.selectedValue = v.val;
                        self.state.$el.append(
                            $("<option></option>").
                                text(v.text).
                                val(v.val)
                        );
                    });
                    self.state.$el.val(self.state.selectedValue);
                    self.state.originalItemData = data;
                    self.state.filteredItemData = data;
                    if (this.state.searchContainer !== null)
                        this.state.searchContainer.show();
                    self.createItems();
                },
                onAjaxLoadError: function (self, data) {
                    self.setAjaxIndicator(true);
                },
                onSelectLiClicked: function (e) {
                    var self = e.data.self,
                        item = $(e.currentTarget);
                    self.state.dropdown.find("li").each(function () {
                        $(this).removeClass("selected");
                    });
                    item.addClass("selected");
                    self.state.selectBox.html(item.text());
                    self.state.selectedValue = item.attr("data-value");
                    self.state.$el.val(self.state.selectedValue);
                    self.state.$el.trigger("change");
                },
            };
            $.fn.tinyselect = function (options) {
                if (typeof (options) != "undefined") {
                }
                return this.each(function () {
                    var sel = Object.create(TinySelect);
                    sel.init($(this), options);
                });
            };
        }(jQuery));
    </script>
    <style>
        .tinyselect {
            height: 34px;
            display: inline-block;
            min-width: 200px;
            position: relative;
        }

            .tinyselect .selectbox {
                position: absolute;
                height: 100%;
                width: 100%;
                text-align: left;
                border: 1px solid #ccc;
                line-height: 32px;
                padding-left: 10px;
                box-sizing: border-box;
                cursor: pointer;
                border-radius: 3px;
                white-space: nowrap;
                overflow-x: hidden;
            }

                .tinyselect .selectbox::after {
                    content: ' ';
                    position: absolute;
                    right: 0px;
                    border-left: 1px solid #ccc;
                    height: 100%;
                    font-size: 10pt;
                    line-height: 34px;
                    padding: 0px 8px;
                    width: 10px;
                    background-color: #eee;
                    background-repeat: no-repeat;
                    background-position: center;
                    background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAAJCAYAAADkZNYtAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuOWwzfk4AAABXSURBVChTjY0BCYBAFMWugw3MYRAbmMROhjGDFXQTThSfcoNx/P8HV2DEvUG7kxVTUPV+MWCKqt4fLJhC9y96TLH7yIz30PmTDjc09HX+ZUJj3ybC96UczHIuzhJ1BlkAAAAASUVORK5CYII=');
                }

                .tinyselect .selectbox.open::after {
                    content: ' ';
                    background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAAJCAYAAADkZNYtAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuOWwzfk4AAABYSURBVChTY8ABWqE0QZAOxP+hNF4gDMTvgBikGESD+DgByHqQQhjG6RwlIEZWCMMgcQywA4ixKQaJowAbIMamEIZB8nBwB4ixKYJhkDwYRAAxNgVomCECALjaLs5bhaybAAAAAElFTkSuQmCC');
                }

            .tinyselect .dropdown {
                position: absolute;
                width: 100%;
                top: 33px;
                border: 1px solid #ccc;
                background-color: white;
                z-index: 100;
                box-sizing: border-box;
                max-height: 200px;
                overflow-x: hidden;
                overflow-y: scroll;
            }

                .tinyselect .dropdown .searchcontainer {
                    padding: 5px;
                }

                .tinyselect .dropdown .searchbox {
                    width: 100%;
                    border: 1px solid #ccc;
                    font-size: 10pt;
                    line-height: 2em;
                    padding: 0 5px;
                }

                .tinyselect .dropdown .searchicon {
                    position: absolute;
                    top: 12px;
                    right: 8px;
                    width: 14px;
                    height: 14px;
                    background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuOWwzfk4AAADESURBVDhPnZLBDcIwDEW7DIt0CmZgBW5tc2AAFugWDNB7FuDMAB0g+FV25AQLJA5Prb797djJUEoJmabptCzLVVjneb4Lo483yYYadqF0bBQkJzJdSJIOT/7RtPuKLmS0yPgCq+zhyGq+NYGU0tkCXvdQVNh68TgmX697JJahEf/uaAEWE80oMbb9OSPJus1jq5zA6SxmR0erJhFGM30h20kOk85WL5wCWogu3N9q3Y3QFM3Xw8D+adUn9QtvfEQJMWV4A2WMBVG/g0M8AAAAAElFTkSuQmCC');
                }

            .tinyselect .itemcontainer {
                list-style: none;
                margin: 0;
                padding: 0;
            }

                .tinyselect .itemcontainer > li {
                    padding: 5px 2px;
                }

                    .tinyselect .itemcontainer > li.item {
                        padding: 5px 10px;
                    }

                    .tinyselect .itemcontainer > li.selected {
                        background-color: #eee;
                    }

                    .tinyselect .itemcontainer > li.item:hover {
                        background-color: #1b6eab;
                        color: white;
                    }

                .tinyselect .itemcontainer li.loadindicator {
                    padding: 15px;
                    font-weight: bold;
                }

                .tinyselect .itemcontainer li.loaderrorindicator {
                    padding: 15px;
                    font-weight: bold;
                    color: red;
                }
    </style>
    <title>How to set filter functionality in dropdown using textbox using JavaScript and CSS</title>
</head>
<body>
    <form runat="server">
        <div class="container">
            <asp:DropDownList ID="select1" runat="server">
                <asp:ListItem Selected="True">Select a State</asp:ListItem>
                <asp:ListItem>Andhra Pradesh</asp:ListItem>
                <asp:ListItem>Arunachal Pradesh</asp:ListItem>
                <asp:ListItem>Assam</asp:ListItem>
                <asp:ListItem>Bihar</asp:ListItem>
                <asp:ListItem>Chhattisgarh</asp:ListItem>
                <asp:ListItem>Gujarat</asp:ListItem>
                <asp:ListItem>Haryana</asp:ListItem>
                <asp:ListItem>Himachal Pradesh</asp:ListItem>
                <asp:ListItem>Jammu & Kashmir</asp:ListItem>
                <asp:ListItem>Karnataka</asp:ListItem>
                <asp:ListItem>Kerala</asp:ListItem>
                <asp:ListItem>Madhya Pradesh</asp:ListItem>
                <asp:ListItem>Maharashtra</asp:ListItem>
                <asp:ListItem>Manipur</asp:ListItem>
                <asp:ListItem>Meghalaya</asp:ListItem>
                <asp:ListItem>Mizoram</asp:ListItem>
                <asp:ListItem>Nagaland</asp:ListItem>
                <asp:ListItem>Odisha</asp:ListItem>
                <asp:ListItem>Punjab</asp:ListItem>
                <asp:ListItem>Rajasthan</asp:ListItem>
                <asp:ListItem>Sikkim</asp:ListItem>
                <asp:ListItem>Tamil Nadu</asp:ListItem>
                <asp:ListItem>Telangana</asp:ListItem>
                <asp:ListItem>Tripura</asp:ListItem>
                <asp:ListItem>Uttarakhand</asp:ListItem>
                <asp:ListItem>Uttar Pradesh</asp:ListItem>
                <asp:ListItem>West Bengal</asp:ListItem>
            </asp:DropDownList>
            <script>
                /* This parser won't respect "---" selection */
                function dataParserA(data, selected) {
                    retval = [{ val: "-1", text: "---" }];

                    data.forEach(function (v) {
                        if (selected == "-1" && v.val == 3)
                            v.selected = true;
                        retval.push(v);
                    });
                    return retval;
                }
                /* This parser let's the component to handle selection */
                function dataParserB(data, selected) {
                    retval = [{ val: "-1", text: "---" }];
                    data.forEach(function (v) { retval.push(v); });
                    return retval;
                }
                /* Create select elements */
                $("#select1").tinyselect();
                $("#havoc").show()

            </script>
        </div>
    </form>
</body>
</html>



Out-Put:-


How to set filter functionality in dropdown using textbox using JavaScript and CSS   How to set filter functionality in dropdown using textbox using JavaScript and CSS Reviewed by NEERAJ SRIVASTAVA on 4:57:00 PM Rating: 5

No comments:

Powered by Blogger.