How can I implement a single-column search feature in a GridView using Javascript in ASP.NET?

I found a Google function for client-side searching in a grid using a textbox

Here is the function:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
        function searchFunction(phrase, _id) {
            var words = phrase.value.toLowerCase().split(" ");
            var table = document.getElementById(_id);
            var ele;
            for (var r = 1; r < table.rows.length; r++) {
                ele = table.rows[r].innerHTML.replace(/<[^>]+>/g, "");
                var displayStyle = 'none';
                for (var i = 0; i < words.length; i++) {
                    if (ele.toLowerCase().indexOf(words[i]) >= 0)
                        displayStyle = '';
                    else {
                        displayStyle = 'none';
                        break;
                    }
                }
                table.rows[r].style.display = displayStyle;
            }
        }

    </script> 

To call this function from a textbox, use the following code:

<asp:TextBox ID="txtSearch" TabIndex="2"  onkeyup="searchFunction(this, '<%=GridView1.ClientID %>');" runat="server"  AutoPostBack="True"/>

The Gridview used for searching looks like this:

 <asp:GridView ID="GridView1"  runat="server"  AutoGenerateColumns="False"    >
                                            <Columns>
<asp:BoundField DataField="ClassName" HeaderText="Class Name" />
<asp:BoundField DataField="PerWeekClass" HeaderText="Week Classes" />
<asp:BoundField DataField="SubID" visible="false" />
                                            </Columns>
                                           </asp:GridView>

The issue I encountered with this function is that it searches strings from all columns of the grid instead of just the first column.

I am not very familiar with JavaScript, so I would appreciate any help or suggestions to resolve this problem.

Thank you in advance!

Answer №1

Feel free to experiment with the following code snippet...

.aspx

    <asp:TextBox ID="txt" runat="server" onkeyup="filter(this);"></asp:TextBox>

    <br />

    <asp:GridView ID="gv" runat="server" Width="100%" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundField DataField="Filter" />
            <asp:BoundField DataField="Name" />
        </Columns>

    </asp:GridView>

Javascript

function filter(txt) {
        var grid = document.getElementById("<%=gv.ClientID %>");
        var row = grid.rows.length;
        var filterValue = txt.value.toLowerCase();
        var splitter = filterValue.split(' ');
        var display = '';
        var currentRowValue = '';

        for (var i = 1; i < row; i++) {
            display = 'none';
            currentRowValue = grid.rows[i].cells[0].innerText;

            for (var j = 0; j < splitter.length; j++) {
                if (currentRowValue.toLowerCase().startsWith(splitter[j]))
                    display = '';
                else {
                    display = 'none';
                    break;
                }
            }
            grid.rows[i].style.display = display;
        }
    }

Code Behind

protected void Page_Load(object sender, EventArgs e)
{
    // Verify
    if (!IsPostBack)
    {
        // Declarations
        DataTable dt = new DataTable();
        dt.Columns.Add("Filter");
        dt.Columns.Add("Name");

        // Populate
        dt.Rows.Add("Do", "Doraemon");
        dt.Rows.Add("No", "Nobita");
        dt.Rows.Add("Si", "Sizuka");
        dt.Rows.Add("Sin", "Sinyu");

        // Bind data
        gv.DataSource = dt;
        gv.DataBind();
    }
}

Answer №2

Modify

element = table.rows[row].innerHTML.replace(/<[^>]+>/g, "");

From

element = table.rows[row].cells[0].innerHTML.replace(/<[^>]+>/g, "");

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

Interact with an external JavaScript function using a button within a web application

I have a JavaScript file called dmreboot_service.js in my /js folder. By running this file with the command node /js/dmreboot_service.js, it successfully triggers a direct method in Azure. My goal is to be able to run this function or file when a button o ...

Choosing an array from the MongoDB database

{ "_id": "4f609932615a935c18r000000", "participants": [ { "user_name": "john1", "role": "user", "created_at": { "sec": 1331730738, "usec": 810000 }, { "user_name": "john2", "role": ...

Embed API requests using JavaScript's Axios library to ensure the correct promise is returned

I am currently facing an issue with posting data to my API using axios. In order to make the request, I need to include a XSFR-token along with it. The technologies I am using for this are React, Redux, Thunk, and Axios. The problem lies in handling this ...

What is the process of transforming a string into a JSON object?

var str = '""{""as"":""N9K-93180YC-EX""}""'; I attempted to remove the extra quotes using a regular expression: var str1 = str.replace(/\"/g, ""); After removing the extra quotes, the string now looks like "{as:N9K-93180YC-EX}". However, ...

Python Selenium: Cannot Click on Element - Button Tag Not Located

TL,DR: My Selenium Python script seems to be having trouble "clicking" on the necessary buttons. Context: Hello. I am working on automating the process of logging into a website, navigating through dropdown menus, and downloading a spreadsheet. Despite ...

"Even when hidden, an HTML Div element still occupies space on the

I encountered an issue with my tabbedPage setup. Even though I have hidden content, it still occupies space on the page. Here is the code snippet that I am using: let tabHeader = document.getElementsByClassName("tabbedpage-header")[0]; let tabIndicator = d ...

The consistency of values remains constant throughout all Ajax requests

I am presenting the code snippet below: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" ...

Utilizing the JavaScript map method to structure API response data

Here is the JSON data I have: { "result": [{ "name": "a", "value": 20, "max": 100, "sale_value": [{ "no": 1, "name": "aaaaa", "price": 200 }, { "no": 2, ...

Why isn't jQuery working properly for showing/hiding elements?

I am attempting to create a functionality where the string remove field can be toggled to show or hide using a single button, depending on its current state. Initially, it should be hidden (using the hidden HTML attribute), and upon clicking the button, it ...

JavaScript Glitches

Embarking on the journey of web design and programming, I am venturing into the world of creating a simple gallery using JavaScript. Despite the convenience offered by jQuery, unfortunately, it is off-limits for this particular assignment. The challenge l ...

Tips for integrating google's api.js file into my vue application

Currently, I am in the process of integrating Google Calendar into my Vue project. The steps I am following can be found at this link. Additionally, I came across an example code snippet at this URL. This is how my Vue file looks: <template> <d ...

Switch the scroll direction in the middle of the page and then switch it back

Yesterday, while browsing online, I stumbled upon this website and was amazed by the unique scroll direction change from vertical to horizontal mid-page. I'm curious about how they managed to achieve that effect. Does anyone have insight into the pro ...

Adding 7 days to a JavaScript date

Can you spot the bug in this script? I noticed that when I set my clock to 29/04/2011, it displays 36/4/2011 in the week input field! The correct date should actually be 6/5/2011 var d = new Date(); var curr_date = d.getDate(); var tomo_date = d.getDate( ...

Develop a nested json object within another json object and send it back to Ajax

In my c# code, I am currently working with a List of Translations structured like this: public class Translations { public string en { get; set; } public string de { get; set; } } Now, I need to convert it into a Json Object because the function ...

What is the limit on the amount of input data (in CSV or JSON format) that can be used to create a

Attempting to visualize a large dataset using D3.js has posed a challenge for me. The data size is 261 MB with approximately 400,000 rows in CSV format. Even when I attempt to run it with just 100,000 rows, the visualization does not appear on the browser. ...

The PHP on server could not be loaded by Ajax

Trying to establish a PHP connection, encountering an error and seeking assistance. The error message displayed is as follows: { "readyState": 0, "status": 0, "statusText": "NetworkError: Failed to execute 'send' on 'XMLHttpReq ...

Harness the Power of JSON in your JavaScript Applications

I have come across many examples on Stack Overflow discussing how to parse JSON into a JavaScript object or convert JSON to a JS object. However, I haven't found an example that demonstrates binding JSON to an already defined JS object. I am currently ...

Steps for storing API information in localStorage:1. Retrieve the API data

My app is running sluggish due to the excessive API calls for information retrieval. To optimize performance, I want to create a unified object containing all the data that can be shared across pages and accessed from localStorage, thus enhancing the app ...

Code for a regular expression that permits either letters or numbers with symbols

Here is the code snippet I am using for data validation in jQuery: return /^(?=.*[A-Za-z0-9/\$#.-_])[A-Za-z0-9/\$#.-_]$/i.test(value) The requirement is that the value should begin with letters or numbers, or a combination of both. Afterwards, ...

Maximizing HTML5 Game Performance through requestAnimationFrame Refresh Rate

I am currently working on a HTML5 Canvas and JavaScript game. Initially, the frames per second (fps) are decent, but as the game progresses, the fps starts decreasing. It usually starts at around 45 fps and drops to only 5 fps. Here is my current game loo ...