Searching for data in a bootstrap table that is not case-sensitive

Searching for and highlighting text within a bootstrap table has proven to be a challenge.

Check out the Fiddle for an example: https://jsfiddle.net/99x50s2s/74/

HTML

<table class='table table-bordered'>
    <thead>
        <tr><th>ID</th><th>Name</th></tr>    
    </thead>
    <tbody id='UserInfoTableBody'>
        <tr><td>1</td><td>UserName 1</td></tr>  
        <tr><td>2</td><td>UserName 2</td></tr>  
        <tr><td>3</td><td>UserName 1</td></tr>  
        <tr><td>4</td><td>UserName 3</td></tr>  
        <tr><td>5</td><td>UserName 2</td></tr>  
        <tr><td>6</td><td>UserName 2</td></tr>  
        <tr><td>7</td><td>UserName 1</td></tr>  
        <tr><td>8</td><td>UserName 1</td></tr>  
        <tr><td>9</td><td>username 2</td></tr>  
    </tbody>
</table>

JS

HighlightMatches();

function HighlightMatches(){

var textToMatch = 'UserName 2';

$('.match').replaceWith(function () {
    return this.innerText;
  });     

$('#UserInfoTableBody td').each(function (i, tdContent) {
    var $td = $(tdContent);
    $td.html($td.html().
             split(textToMatch).
             join('<span class="match">' + textToMatch + '</span>'));
});

}

CSS

.match{background-color:yellow;}

Issue:

The current search is sensitive to case and I need it to be case-insensitive. The code above searches for 'UserName 2', but misses the value in the last row ('username 2').

I attempted to use 'contains', but I'm unsure how to properly highlight the text. Any assistance on this matter would be greatly appreciated.

Expectation

The goal is to only highlight the text that matches the search criteria. This should function properly for,

var textToMatch = '2';
var textToMatch = 'User';
var textToMatch = 'user';

Answer №1

If you want to achieve this, the following code snippet can be used:

HighlightMatches();

function HighlightMatches(){

    var textToMatch = 'username';

    $('.match').replaceWith(function () {
        return this.innerText;
      });     

    $('#UserInfoTableBody td:odd').each(function (i, tdContent) {
        var $td = $(tdContent);
        var pos = $td.html().toLowerCase().search(textToMatch);
        var len = textToMatch.length;
        if(pos != -1 ){
            var match = $td.html().substring(pos, len+pos);
            var splitted = $td.html().split(match);
            $td.html(splitted[0] + '<span class="match">' + match + '</span>' + splitted[1]);
        }
    });
}

For a live demo, you can check the Fiddle link: https://jsfiddle.net/99x50s2s/87/

Answer №2

One way to achieve this is by utilizing the toLowerCase() method.

By applying this function, all characters within the specified strings will be converted to lowercase. Make sure to implement this for both the textToMatch and td elements.

Best of luck!

Answer №3

$.extend($.expr[":"], {
"containsIN": function(elem, i, match, array) {
return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});

HighlightMatches();

function HighlightMatches(){

    var textToMatch = 'UserName 2';

    $('.match').replaceWith(function () {
        return this.innerText;
      });     

    $('#UserInfoTableBody td').each(function (i, tdContent) {
         $('td:containsIN("'+textToMatch+'")').html('<span class="match">' + textToMatch + '</span>');
    });
}

Give this a shot. https://jsfiddle.net/99x50s2s/85/

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

Internet Explorer experiencing problems with JSON when using ajax请求

After struggling with this issue for a significant amount of time, I have decided to seek help from the community. I am utilizing Google Custom Search REST API in combination with jQuery to retrieve results and display them in the browser. The problem I a ...

What is the best location to insert CSS in an HTML document?

I tried to customize the CSS on my Blogger blog, but unfortunately, I am unable to access the theme designer. As a result, I attempted to add CSS directly into the code using tags. However, I am having trouble locating the tag within the HTML file. This is ...

Saving the chosen outcome to a collection for easy export in JSON format

I've developed an Angular application that interacts with the Spotify API for searching purposes. The search results are displayed and users can add their selected choices to a list on the right by clicking on a + sign. Currently, I am able to perform ...

What could be causing my JavaScript alert to not appear on the screen?

Essentially, I've been attempting to trigger a Javascript alert using PHP. However, the alert isn't functioning at all. This is my echo statement that dynamically generates the alert echo "<script>alert('Uploaded file was not in the ...

What is the best way to switch from http to https in a React application?

When performing audits in Chrome, I encountered a net::ERR_EMPTY_RESPONSE error because Lighthouse was not able to consistently load the requested page. Google developers have recommended configuring my server (possibly node.js) to redirect from http to ht ...

dissecting mongo queries using nodes

I am thinking about organizing my mongo db queries into a separate js file to make it easier to reuse the code. I have tried the format below but it doesn't seem to work. Does anyone have any suggestions on how I could accomplish this? queries.js va ...

Is it possible to utilize AJAX to load the URL and then extract and analyze the data rather than

I had originally created a web scraping method using PHP, but then discovered that the platform I was developing on (iOS via phone gap) did not support PHP. Fortunately, I was able to find a solution using JS. $(document).ready(function(){ var container ...

Can you identify the issue with the phase control in my sine wave program?

I have recently developed an interactive sine wave drawing web application. Below is the code snippet for reference: const canvas = document.getElementById("canvas"), amplitude_slider = document.getElementById("amplitude_control"), wavelength_slider ...

Is there a way to remotely access and read text files stored on a server using either JavaScript or Ajax from an IIS6.0 Virtual directory?

Is it possible to use JavaScript or Ajax to read the text from a file on a remote machine (from IIS6.0 Virtual directory) and then copy it into a specific folder on the client machine? ...

Leveraging redux within your NEXT.JS project

While working on my Next.js application, I have integrated Redux and Redux Saga. I am trying to incorporate server-side rendering for making HTTP requests: export const getStaticProps = wrapper.getStaticProps(async ({ store }) => { store.dispatch(g ...

Executing a function when an item is dragged in jQuery UI sortable

I have a "draggable" block and a "sortable" block. What I am trying to achieve is to trigger an action through jQuery when I drag an item from the "sortable" block. Below is the JavaScript code I am currently using: $(".sortableList").sortable({ }); ...

Tips on attaching a suffix icon to a material-ui-pickers input box

Here is a snippet of my code: <Box p={6}> <Grid container spacing={2}> <Grid item xs={6}> <TimePicker autoOk label={t('checkIn')} value={time1} onChange={handlecheckIn} clearable /> </Grid> < ...

Selecting any of the bar chart labels will reveal just a two-day timeframe

My bar chart is behaving strangely - when I click on all labels, it only shows two days instead of updating as expected. I suspect it may be due to a bad implementation involving parsing. Can anyone provide assistance? I have created a minimum example on ...

When using $.mobile.changePage($(""), the new web page will always be loaded

I am struggling to make the $.mobile.changePage() function work correctly. The issue is that when I navigate from a page called "report outage" to another page named "new outage" and then return to the "report outage" page, clicking the add button always t ...

What causes the device pixel ratio to vary across different web pages on the same device and operating system?

I am curious about why device pixel ratio varies between different websites and operating systems. For instance, when using the same device, this site displays a different pixel ratio on Windows compared to Ubuntu. On Windows, the pixel ratio is 1.34 whi ...

Top tip for receiving a JSON response object using AngularJS

I am currently working with an API that returns a json array object. In my Controller, I have been able to retrieve the json data successfully using the following code: angular.module('lyricsApp', []) .controller('LyricsController', [& ...

What is the best way to populate a dropdown menu in PHP?

I am trying to populate my combobox with names from an SQL database. I came across some code on W3schools, but I am having trouble integrating it into my own code. Currently, the combobox is filled with select, but that's not the intended functionalit ...

Notify customer upon database update

I'm working on developing a messaging system in asp.net. How can I notify the client when there is a change in the database? For instance, if a user's page is open and another user sends them a message, how can the software alert the user? Is it ...

Using functions as properties in React.js

I am facing an issue while trying to pass a function as a prop. Although I have done this successfully in the past, now I am getting an error (this.props.functionName is not a function). I have a child component called Navbar and a parent component named ...

Tips for customizing fonts in a WordPress object

WordPress is sending me an object that I need to work with. The main issue at hand: the font styles of WordPress posts in my app are all inconsistent. How can I go about styling these fonts uniformly? Take a look at this Plunkr if you'd like to expe ...