Toggle the visibility of image elements depending on the input entered in the search bar using jQuery

I have a photo gallery grid and I am looking to implement a search functionality for an img tag's 'data-title' value, where only images with matching data will be displayed. For example, if I type "hay" into the search box, only the image below should appear, while all other images without "hay" in their data-title will be hidden.

<a href="photo_gallery\photos\01.jpg" data-lightbox="gallery" data-title
 ="Hay Bales - I love hay bales. Took this snap on a drive through the 
 countryside past some straw fields.">
    <img src="photo_gallery\photos\thumbnails\01.jpg" alt="fields">
</a>  

I tried customizing some code found here to hide divs but ran into difficulty when trying to search the data-title attribute. Every time I type something in the search box, all images get hidden regardless of their data-title attribute.

$('#search').keyup(function() {

    var value = $(this).val();
    var exp = new RegExp(value);

    $('a').each(function() {
        var isMatch = exp.test($('a[data-title='+value+']', this).text());
        $(this).toggle(isMatch);
    });
});

Can someone point out what I might be doing wrong here? This is how the search bar is currently structured.

 <div class="searchBar">
   <input type="text" name="search" id="search" placeholder="Search">
 </div>

Answer №1

To ensure accurate results, it is important to consider that anchor tags without text nodes may not work effectively with the JQuery .text() method. Therefore, it is recommended to target the element's data attribute and utilize it as the basis for your regular expression test.

$('#search').keyup(function() {

    var value = $(this).val();
    var exp = new RegExp(value);

    $('a').each(function() {
        var isMatch = exp.test($(this).data('title'));
        $(this).toggle(isMatch);
    });
});

Answer №2

A different approach could be to completely eliminate the use of RegExp since you have an html5 data set available. You can directly compare the values if needed.

Here is an example:

https://jsfiddle.net/abc123/xzy789lmn/4/

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

react-router is unable to navigate to the desired page

I am currently using react-router-dom in my project, but I am still relatively new to it. I have encountered an issue regarding page navigation. Below is the code for my App.js: class App extends Component { render() { return ( <div classN ...

React: When state is updated and a console.log is used, the console displays the previous state instead of the updated

Upon clicking the button, a peculiar sequence unfolds - the console displays 0 and the page refreshes to show 1 function App() { const [count, setCount] = useState(0); const addOne = () => { setCount(count + 1) console.log(count) } ...

Storing a selected database column as a variable from an HTML page in Node.js with Express

My website showcases flight information pulled from a MySQL database. The process begins with a form where users select destinations and dates for their desired flight. Once the form is submitted, users are directed to another page where flights matching t ...

The alignment of Material-UI Button and ButtonGroup is not consistent

I'm puzzled as to why the Button and ButtonGroup elements are not aligned on the baseline in the code snippet provided. Is there a specific property that can be adjusted on the ButtonGroup element to achieve alignment? <!DOCTYPE html> <htm ...

Uploading a file to a URL using Node.js

Looking for a way to replicate the functionality of wget --post-file=foo.xpi http://localhost:8888/ in nodejs, while ensuring it's compatible across different platforms. In need of assistance to find a simple method for posting a zip file to a specif ...

A directive containing a template

I'm facing a unique challenge where I have to nest a template inside another template within my directive. The issue arises because AngularJS doesn't recognize ng-repeat code inside attributes. In an ideal scenario, here is how I envision my cod ...

Two functions that require multiple clicks to execute

My JavaScript code requires two consecutive clicks to function properly for some reason. Here is the code for the link: <a href="" onclick="select_all_com(); return false">Select All</a> Now, here is the code for the function that is called w ...

Unable to employ Javascript while utilizing AJAX within jQuery Mobile

Exploring the potential of Swiper Javascript Api from within Jquery Mobile raises some challenges. The compatibility issues with Ajax in Jquery Mobile complicate the execution of Javascript functions. This becomes evident when examining example source cod ...

I seem to be having trouble with my JavaScript code when attempting to search for items within

I want to implement an onkeyup function for a text input that searches for patient names from column 2 in my table. However, it seems to be not working properly as I don't get any results in return. Below are the snippets of what I have done so far. ...

Modify the behavior of the tab key using JavaScript

I'm currently working on a text editor embedded within a contenteditable div. My goal is to modify the [TAB] functionality so that instead of shifting focus to the next element (as is done by default in browsers), it will either insert spaces or a &b ...

When attempting to redirect to a different page using setTimeout, the loading process appears to continue indefinitely

Currently, I am utilizing the following script: setTimeout(function(){ window.location.href = '/MyPage'; }, 5000); While this script successfully redirects me to /MyPage, it continuously reloads every 5 seconds. Is there a way to r ...

instructions on implementing Arial Black font style in LESS

Using less-1.7.0.min.js, I encountered an issue when setting Arial Black as the font. @fontFamily: Arial Black,Arial Black,Gadget,sans-serif; Upon generating the CSS, it resulted in: p, span { font-size: 14px; font-family: Arial #000000, Arial #000000, ...

What steps should I take to create a stylish HTML profile with well-organized CSS?

Looking for a way to display photos, biographies, personal details, and more on a webpage? We've got you covered! You can customize the layout using semantic HTML and CSS styles. Build your design online at http://jsfiddle.net/ and thank us later! &l ...

What is the best way to adjust the responsiveness of my AppDrag page for mobile optimization?

My landing page is all set up, but I'm looking to tweak the font sizes and spacing for mobile users. Can these changes be made using design tools instead of digging into the code? ...

Stop the color buffer from being automatically cleared in WebGL

Removing gl.clearColor(c[0],c[1],c[2],1.0); gl.clear(gl.COLOR_BUFFER_BIT ); does not stop the screen from getting cleared at the start of the next draw cycle. Is there a method to avoid this situation? I am aiming for an overpaint effect. ...

Reloading a page in Vue-Router after submitting a form

Learning Vue by creating a movie searcher has been quite challenging. The issue I'm facing is that I'm using the same component for different routes with path params to fetch specific information. However, when I submit a form with a query for t ...

Change the border color of radio buttons when clicked

When one of the radio buttons is clicked, it should give an outer border with color. When the other radio button is clicked, it should give an inner border that surrounds the image. <!DOCTYPE html> <html> <head> ...

Transmitting information to the service array through relentless perseverance

I need assistance finding a solution to my question. Can my friends help me out? What types of requests do I receive: facebook, linkedin, reddit I want to simplify my code and avoid writing lengthy blocks. How can I create a check loop to send the same ...

Prevent the rendering of HTML in the combobox dropdown menu

Utilizing ExtJs 3.1 In my Ext.form.ComboBox, the store includes values such as: "value1", "<value2>", "value3". The issue arises when the combobox dropdown list is displayed, and "<value2>" is being interpreted as an HTML tag. This is causing ...

Guide on positioning an SVG button within a form

I am attempting to design a form with two input fields and a button. Rather than using a plain text button, I prefer to utilize an SVG graphic for the button; however, it is not aligning correctly. Consider the following HTML and CSS: body { backg ...