Interactive search tool for toggling visibility of elements

Hello everyone, this is my initial post on StackOverflow. Keeping my fingers crossed that it goes smoothly!

<input type="Text" id="filterTextBox" placeholder="Filter by name"/>
<script type="text/javascript" src="/resources/events.js"></script>
<script>
$("#filterTextBox").on("keyup", function () {
    var search = this.value;
    $(".kurssikurssi").show().filter(function () {
        return $(".course", this).text().indexOf(search) < 0;
    }).hide();        
});

</script>

I have integrated a JavaScript snippet similar to this in my school project, you can check it out here:

The search bar at the bottom of the page is designed to filter divs and only display those containing a specific keyword. For instance, if you enter "Digital Electronics," it will only show divs with text "Digital Electronics II" and "Digital Electronics." Currently, when I input random characters, everything hides as expected. However, if I start typing the beginning of a course name, it fails to hide courses that do not match the text string.

I have included an example that I found useful (link): http://jsfiddle.net/Da4mX/

It's a bit tricky to explain, but I hope you'll understand once you try using the search functionality on my site. As a beginner in JavaScript, I grasp setting the searchbox string as 'var search,' but the other details are fuzzy for me.

I would greatly appreciate any assistance in dissecting the script, identifying where I might be making mistakes, and suggesting how to resolve the issue.

Answer №1

It seems like in this scenario, you are toggling the visibility of the course parent element based on user input.

$("#filterTextBox").on("keyup", function () {
    var query = $(this).val().trim().toLowerCase();
    $(".course").show().filter(function () {
        return $(this).text().toLowerCase().indexOf(query) < 0;
    }).hide();        
});

Answer №2

Give this a try, it's currently working. Simply paste the code below into your console and test it out by searching.

$("#filterTextBox").on("keyup", function () {
    var search = this.value;  
    if( search == '') { 
        return 
    } 
    $( ".course" ).each(function() {
        a = this; 
        if (a.innerText.search(search) > 0 ) {
            this.hidden = false
        } else {
            this.hidden = true
        }
    }); })

Give it a go and see that the search function is indeed now operational.

Answer №3

The root of your issue lies here:

return $(".course", this)

According to the jQuery documentation: http://api.jquery.com/jQuery/#jQuery-selection

Internally, selector context is implemented with the .find() method, so $( "span", this ) is equivalent to $( this ).find( "span" )

The filter function already checks each element individually. Therefore, when you attempt to place $(".course") within the context, it will retrieve all elements again...

A more efficient solution would be:

$("#filterTextBox").on('keyup', function()
{
    var search = $(this).val().toLowerCase();
    $(".course").show().filter(function()
    {
        return $(this).text().toLowerCase().indexOf(search) < 0;
    }).hide();
});

Alternatively, you can use the :contains() CSS selector, but it may not be optimized for a large list and might not work across all browsers.

http://caniuse.com/#search=contains

Answer №4

Your previous approach to accessing elements was incorrect. The following code should now work:

$(".kurssikurssi").find('.course').show().filter(function () {
      var $this = $(this)
      if($this.text().indexOf(search) < 0){
              $this.hide()
      }
 })

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

Resizing the Vue page to fit the viewport and using Flexbox to anchor the footer to the bottom

My Vue.js page structure consists of a navigation bar, main body content, and a footer: <template> <div class="flex_container"> <div class="container_navigation"> <nav-bar /> </div> < ...

Issue - The module ./en.json could not be located when using the vue-i18n plugin

I recently integrated the i18n plugin into my existing Vue project to add localization. After following all the installation instructions from various sources (such as here), I made sure that each locale has its own file under /src/locales with the correct ...

Switching the visibility of multiple textareas from block to none

I am currently exploring ways to make one text area disappear while another one appears in its place. With limited knowledge of Javascript and just starting my journey into HTML and CSS, I am reaching out to the forum for assistance or guidance on the rig ...

Choose an option with JavaScript once the request is successful

Choose the day, month, and year using JSON data success: function(jsondata){ var data=JSON.parse(jsondata); var list_html="<div id='editrelation'><label id='dateLabel' style='display:none&apo ...

CSS Hue Rotate is causing the image to appear darker

The CSS filter hue-rotate seems to be darkening my image according to my observations. For an example, visit: https://jsfiddle.net/m4xy3zrn/ Comparing images with and without the filter applied, it’s clear that the filtered one appears much darker than ...

Analyzing critical code paths for optimal performance

There is a function that accepts two arguments and an optional third argument. The function should return true if the first argument is greater than the second, false if not, unless the third argument is true, in which case it should return true if the fir ...

How can you retrieve newly added DOM elements from a PartialView using Ajax.BeginForm?

Below is a snippet of code that loads a Partial View within a div element: <div id="_customerForm"> @Html.Partial("~/Views/Customer/_customerForm.cshtml", Model.customerForm) </div> The Partial View contains an Ajax Form as shown ...

Eliminate the unnecessary code repetition in my functions using Typescript

I have 2 specific functions that manipulate arrays within an object. Instead of repeating the same code for each array, I am looking for a way to create reusable functions. Currently, my functions look like this: setLists(): void { if (this.product.ord ...

What is the process for transmitting data in JSON format generated by Python to JavaScript?

Utilizing Python libraries cherrypy and Jinja, my web pages are being served by two Python files: Main.py (responsible for handling web pages) and search.py (containing server-side functions). I have implemented a dynamic dropdown list using JavaScript w ...

When the drawer is opened, there is a strange phenomenon of all buttons being mysteriously clicked

Currently, I am working on a single-page web application utilizing React and Material UI, along with React-Mini-Router for routing. The app features a side drawer that is activated by clicking a hamburger icon located in the top app bar. Each item in the d ...

Why does this inner HTML table always adjust its width based on the content within it? Is there a way to make it match the width of its container instead

I'm not very familiar with HTML and CSS, and I've come across a problem. Here is the CSS structure in question: <!-- TECHNICAL REFERENCE: --> <div id="referenteTecnicoTab"> <table width="800px" class="standard-table-cls table-he ...

Having trouble importing from the public folder in CSS with Create React App?

While working on a project initialized with Create React App, in the public folder there is an assets directory containing a file named logo512.jpg. When I use this file in a component like so: <div> <img src='/assets/logo512.jpg'/& ...

The search box output will be the same as the JSON result

I have a server in Node.js that is able to read and process a JSON file containing various data, including unique user IDs. I have incorporated a search box into my HTML page, and I am seeking assistance with creating a jQuery method (which will require AJ ...

The website doesn't give my codes enough time to execute fully

I have a series of commands that I need to execute: Retrieve cookie from the browser using the JS Cookie plugin in mypage.php Validate its value with Ajax and my PHP scripts in myapi.php Set certain SESSION variables in myapi.php Utilize the values store ...

Differentiating a path element in SVG by dynamically adding color using d3 and react

I have a unique SVG icon: <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <circle cx="12" cy="12" r="12" /> <path class="svg-fill" d="M12,2A10,10,0,1,0,22, ...

The VueJS component from a third-party source is not located in the node_modules directory

Utilizing vue-cli version 3 for a fresh vuejs project (I've been dedicating ample time to learning vuejs, but this marks my initial attempt at integrating a third-party component). I'm aiming to incorporate a visually appealing grid component. Th ...

"Implementing a 960 Grid System with an HTML5 Header Element

Exploring 960.gs and HTML5 as a beginner has led to some challenges. My current project involves an image spanning 2 grid units, followed by a div taking up 5 units on the same line, with a line break needed before displaying a heading. I attempted the la ...

Unique hover tags such as those provided by Thinglink

Looking for a way to replicate the functionality of Thinglink? Imagine a dot on an image that, when hovered over, displays a text box - that's what I'm trying to achieve. I thought about using tooltips in Bootstrap, but I'm not sure if it ...

I'm curious about how to use JQuery to pinpoint the firstName within a JSON String and retrieve its corresponding ID

Does anyone have an idea about the outcome in the alert? Is it a regular string, an object, or JSON? How can I select one of the entities and find another based on that selection? For example, I want to choose the first name and retrieve the ID from it. It ...

Obtain an image from CSS using :after with jQuery

In my attempt to create a button animation where checkboxes in the .focus state should display their assigned background: url("x.svg"); from the CSS file, I have encountered an issue with my markup. I am struggling to make the :after element appear on the ...