Most efficient way to use JavaScript to filter a checkboxlist

Our project does not require the use of any javascript libraries such as jQuery, Dojo, or Prototype so finding a solution may be more challenging. I am looking for detailed answers to this question explaining how it can be accomplished. As many of you may be aware, an asp.net checkboxlist generates markup in Flow repeatLayout.

<span>
<checkbox><label></br>
<checkbox><label></br>
<checkbox><label></br>
</span>

I have omitted the closing tags for simplicity. There is a textbox for searching through this list of checkboxes. Now, here is my question:

How can I filter the checkboxlist when a user types a search term in the textbox and hide the unmatched checkboxes and labels?

Additionally, I have some related questions that I would like answers to:

  1. Is there any standalone script available for this purpose?

  2. Are there any patterns, articles, or posts explaining issues to consider while implementing search functionality? For example, something like onkeydown do's and don'ts.

  3. My current idea involves having a cached collection of label tags' `innerHTML`, then looping through each tag to check for the search term. When found, hide all others but only show matching ones. However, I am concerned about performance implications with a long list. Is there a better approach that doesn't involve looping on every keypress?

Your suggestions, solutions, scripts, and answers are greatly appreciated.

Answer №1

This unique solution was inspired by Ktash's answer, as I sought to expand my knowledge of javascript, DOM navigation, and RegExp.

I opted to switch the "keypress" event to "keydown" to ensure that backspace/delete actions would still trigger filtering, unlike before.

[CustomPage.html]

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="RealtimeCheckBoxListFiltering.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
  <script type="text/javascript">
    window.onload = function () {
      var tmr = false;
      var labels = document.getElementById('cblItem').getElementsByTagName('label');
      var func = function () {
        if (tmr)
          clearTimeout(tmr);
        tmr = setTimeout(function () {
          var regx = new RegExp(document.getElementById('inputSearch').value);
          for (var i = 0, size = labels.length; i < size; i++)
            if (document.getElementById('inputSearch').value.length > 0) {
              if (labels[i].textContent.match(regx)) setItemVisibility(i, true);
              else setItemVisibility(i, false);
            }
            else
              setItemVisibility(i, true);
        }, 500);

        function setItemVisibility(position, visible)
        {
          if (visible)
          {
            labels[position].style.display = '';
            labels[position].previousSibling.style.display = '';
            if (labels[position].nextSibling != null)
              labels[position].nextSibling.style.display = '';
          }
          else
          {
            labels[position].style.display = 'none';
            labels[position].previousSibling.style.display = 'none';
            if (labels[position].nextSibling != null)
              labels[position].nextSibling.style.display = 'none';

          }
        }
      }

      if (document.attachEvent) document.getElementById('inputSearch').attachEvent('onkeypress', func);  // IE compatibility
      else document.getElementById('inputSearch').addEventListener('keydown', func, false); // other browsers
    };
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <table>
    <tr>
      <td>
        <asp:TextBox runat="server" ID="inputSearch" ClientIDMode="Static" />
      </td>
    </tr>
    <tr>
      <td>
        <asp:CheckBoxList runat="server" ID="cblItem" ClientIDMode="Static" RepeatLayout="Flow" />
      </td>
    </tr>
  </table>
  </form>
</body>
</html>

[CustomPage.aspx.cs]

using System;
using System.Collections.Generic;

namespace RealtimeCheckBoxListFiltering
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            cblItem.DataSource = new List<string>() { "qwe", "asd", "zxc", "qaz", "wsx", "edc", "qsc", "esz" };
            cblItem.DataBind();
        }
    }
}

Answer №2

let timerActive = false;
let labelElements = document.getElementsByTagName('label');
let searchFunction = function() {
    if (timerActive) clearTimeout(timerActive);
    timerActive = setTimeout(function () {
        let regexPattern = new RegExp(inputValue); /* Input value here */
        for(let index = 0, total = labelElements.length; index < total; index++) {
            if(regexPattern.test(labelElements[index].textContent || labelElements[index].innerText)) {
                labelElements[index].style.display = 'block';
            } else {
                labelElements[index].style.display = 'none';
            }
        }
    }, 100);
};
if (document.attachEvent) inputField.attachEvent('onkeypress', searchFunction);
else inputField.addEventListener('keypress', searchFunction, false);

This code snippet serves as a starting point and may need further refinement. A delay of 100 milliseconds is set before executing the loop to avoid running on every keypress but rather after typing stops. You can adjust this duration as needed. Variables for inputField and inputValue are not defined in this example assuming you already know how to obtain them. If your labels dynamically change, consider fetching the list each time.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am having trouble with using document.getElementById().value to retrieve text input. Can anyone help me understand why it's not

It's puzzling to me why document.getelementbyid().value isn't working as expected. Upon inspecting the console, no input seems to be sent or printed out in the console. function callApi() { var keyword = document.getElementById('user_ ...

Loading CSS files conditionally in Angular2's index.html

Currently, my index.html page features a dark theme: <base href="/"> <html> <head> <title>XXX</title> </head> <body> <link rel="stylesheet" type="text/css" href="assets/dark_room.css"> <my-app ...

Integrate dat.GUI directly into a THREE.js scene without the use of an <iframe> tag

When a THREE.js scene takes up the full html page, the dat.GUI is embedded within the scene itself, as shown in this example. However, when the THREE.js scene does not occupy the entire page, positioning the dat.GUI becomes more complicated. The examples ...

The efficiency of upsert operations diminishes as the size of the collection (number of documents) increases

Request Scenario: I am using a REST API to access battle results from a video game. The game is an online team vs team match where each team consists of 3 players who can select from a pool of 100 different characters. My goal is to track the wins, losses ...

What are the benefits of incorporating a mock AJAX call in testing scenarios?

I recently came across a tutorial on TDD React here and I'm having trouble understanding the following test scenario: it('Correctly updates the state after AJAX call in `componentDidMount` was made', (done) => { nock('https://api. ...

When I attempted to download a file by clicking on the download button in a gridview in asp

When attempting to download a file from my database within a gridview, clicking on the download link does not result in anything happening. This is my aspx code: <asp:GridView CssClass="table table-striped responsive" ID="GridView1" runat="server" All ...

Exploring the different pages in React js

I am currently working on implementing a button in React Js that, when clicked, should navigate to another screen. However, I keep encountering an error: TypeError: Cannot read property 'push' of undefined. I have tried various solutions but noth ...

The context provider in Next.js wraps the App component with a layout component specific to each page, resulting in data

Within my project, I have an authentication context component wrapping the main app component. Simultaneously, I am also attempting to implement a page-specific layout component based on the Next.js documentation found here. I'm unsure if my approach ...

What is the process for transferring an environment.json file to the output directory and then utilizing it with Webpack 4?

Our application is expanding with multiple environments and vendors on the horizon. While the traditional approach of running webpack --env.NODE_ENV=myenvironment works for now, it will soon become inefficient. The main objective here is to streamline the ...

"How can you enhance the performance of JavaScript and CSS in a Chrome Extension without using exclude_matches/globs or excluding domains

I have been in the process of creating a Chrome Extension, and unfortunately, when I tried to make it work on specific URLs, I encountered an issue. While Chrome has options like exclude_matches and exclude_globs for this purpose, there seems to be a bug i ...

How come emphasizing certain characters in a string doesn't display the <b> tag in React.js?

I am trying to make a specific part of a string bold in my React.js app, but I'm not getting the expected result. Below is the code I am using and the output it produces: data?.map((item) => (<li key={item.id}>{item.title.replace(new RegExp(v ...

Why is the responseText of an AJAX request empty on Chrome?

Why does this simple AJAX request work in IE but not Chrome? Check out the code below: var x = new XMLHttpRequest(); x.open("GET","style.php",true); x.send(); alert(x.responseText); The last line triggers an empty 'alert' window. Here's ...

I'm currently experiencing a challenge with a project I'm tackling that specifically deals with chart.js

In my recent coding project, I created a script to gather user input and then present it in various chart formats. However, upon executing the code, the selected chart fails to display after inputting values and clicking on the "generate chart" button. Her ...

Tips on using Visual Studio Code to troubleshoot Angular 4 unit tests

I am working on an Angular 4 project with Material design in Visual Studio Code. The setup is done using angular/cli. Currently, I have been writing unit tests using Karma and Jasmine. However, when trying to debug the tests by setting breakpoints, it doe ...

I'm looking for a tag cloud widget that can handle JSON objects. Any suggestions?

Looking for recommendations on widgets that can generate a tag cloud using JSON objects. I have an array of JSON objects and would like to know the most effective method for creating a tag cloud with them. Thanks in advance! =) ...

Receiving communication without the need for port forwarding

My goal is to establish a system where a server can send messages to clients at any given time, ensuring that when a message is sent, it is received almost immediately (ideally within 1 second or less). I am looking for a way to achieve this without having ...

Activate current event on newly added elements

Is it possible to have both blur and keypress(13) trigger the same action on an appended element? I thought using trigger() would work, but it's not. Hopefully, I'm just missing something obvious. $(document).ready (function() { $("#btn").cli ...

freshly opened window shutting down right after its inception

Hello everyone, I've encountered an issue with my code. I'm trying to open the sign-in page from the next-auth library in a new window using the react-new-window library. The problem is that when I click on the button, the new window opens and im ...

Ways to conceal a button within .net 2010?

In my web application, I have a form with a dropdown list and a button. The dropdown list is connected to a database table and contains three options with IDs 1 to 3 (Weekly, Monthly, Please Select). The dropdown list is set to initially display "Please S ...

Choose all div elements with a specified class from a variable

How can I retrieve all div elements with the "test" class from a variable and insert them into another div? var response = xmlhttp.responseText; var selectedDivs = $(response).find('.test'); $('.anotherdiv').prepend(selectedDivs); ...