Common JavaScript file to search and filter DropDownList items in ASP.Net

nauna
 
on Jan 12, 2021 02:54 AM
Sample_707911.zip
631 Views

hello,

I am using this, it works very well 

Filter and Search ASP.Net DropDownList items using JavaScript

I want to create the JavaScript class file so I can just add the reference of JavaScript file and call the function and pass ddl name in JavaScript function so I do not need to call long code on each and every page

Please advice how to make its class file

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jan 12, 2021 06:49 AM

Hi nauna,

Refer below code.

JavaScript

var ddlText, ddlValue, ddl, lblMesg;
function CacheItems(ele,msg) {
    ddlText = new Array();
    ddlValue = new Array();
    ddl = ele;
    lblMesg = msg;
    for (var i = 0; i < ddl.options.length; i++) {
        ddlText[ddlText.length] = ddl.options[i].text;
        ddlValue[ddlValue.length] = ddl.options[i].value;
    }
}

function FilterItems(value) {
    ddl.options.length = 0;
    for (var i = 0; i < ddlText.length; i++) {
        if (ddlText[i].toLowerCase().indexOf(value) != -1) {
            AddItem(ddlText[i], ddlValue[i]);
        }
    }
    lblMesg.innerHTML = ddl.options.length + " items found.";
    if (ddl.options.length == 0) {
        AddItem("No items found.", "");
    }
}

function AddItem(text, value) {
    var opt = document.createElement("option");
    opt.text = text;
    opt.value = value;
    ddl.options.add(opt);
}

HTML

<div>
    <asp:TextBox ID="txtSearch" runat="server"
        onkeyup="FilterItems(this.value)"></asp:TextBox><br />
    <asp:DropDownList ID="ddlItems" runat="server">
        <asp:ListItem Text="Mango" Value="1"></asp:ListItem>
        <asp:ListItem Text="Orange" Value="2"></asp:ListItem>
        <asp:ListItem Text="Apple" Value="3"></asp:ListItem>
        <asp:ListItem Text="Banana" Value="4"></asp:ListItem>
        <asp:ListItem Text="Water Melon" Value="5"></asp:ListItem>
        <asp:ListItem Text="Lemon" Value="6"></asp:ListItem>
        <asp:ListItem Text="Pineapple" Value="7"></asp:ListItem>
        <asp:ListItem Text="Papaya" Value="8"></asp:ListItem>
        <asp:ListItem Text="Chickoo" Value="9"></asp:ListItem>
        <asp:ListItem Text="Apricot" Value="10"></asp:ListItem>
        <asp:ListItem Text="Grapes" Value="11"></asp:ListItem>
        <asp:ListItem Text="Olive" Value="12"></asp:ListItem>
        <asp:ListItem Text="Guava" Value="13"></asp:ListItem>
        <asp:ListItem Text="Sweet Lime" Value="14"></asp:ListItem>
    </asp:DropDownList>
    <br />
    <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
</div>
<script src="JavaScript.js"></script>
<script>
    window.onload = function () {
        var ddl = document.getElementById("<%=ddlItems.ClientID %>");
    var lblMesg = document.getElementById("<%=lblMessage.ClientID%>");
        CacheItems(ddl, lblMesg);
    }
</script>