Utilize jQuery to hide and then show elements based on text input

Recently, I came across a useful jQuery filter example that sparked my interest. To test it out, I created my live example and shared the code on CodePen (or you can check out the Fiddle if you prefer).

One issue I encountered was that after entering text in the input field, the boxes would realign but the numbers wouldn't reappear when the text was deleted unless the page was refreshed. I played around with the code snippet below, but couldn't find a solution. Your help is greatly appreciated!

    $('#sortable').change(
function(){
if ($(this).val().length) {
    $('#number').hide();
}
else {
    $('#number').show();
}

});

Answer №1

Give this a try:- http://jsfiddle.net/adiioo7/nYYBU/10/

JavaScript Code:-

(function ($) {
    jQuery.expr[':'].Contains = function (a, i, m) {
        return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
    };

    function listFilter(header, list) {
        var form = $("<form>").attr({
            "class": "filterform",
                "action": "#"
        }),
            input = $("<input>").attr({
                "class": "filterinput",
                    "type": "text",
            });
        $(form).append(input).appendTo(header);
        $(input).change(function () {
            var list = $("#sortable");
            var filter = $(this).val();
            console.log(filter.length);
            if (filter.length > 0) {
                $(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
                $(".number").hide();
                $(".numberstwo").hide();
            } else {
                console.log($(".number"));
                $(".number").show();
                $(".numberstwo").show();
                $(list).find("a").parent().slideDown();
            }
            return false;
        }).keyup(function () {
            $(this).change();

        });
    }
    $(function () {
        listFilter($("#header"), $("#sortable"));

    });
}(jQuery));

Answer №2

Here's the revised JavaScript code...

Take a look at this Demo Fiddle

(function ($) {
    jQuery.expr[':'].Contains = function (a, i, m) {
        return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
    };

    function filterList(header, list) {
        var form = $("<form>").attr({
            "class": "filterform",
                "action": "#"
        }),
            input = $("<input>").attr({
                "class": "filterinput",
                    "type": "text",
            });
        $(form).append(input).appendTo(header);
        $(input).change(function () {
            var filter = $(this).val();
            if (filter) {
                $(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
                $(list).find("a:Contains(" + filter + ")").parent().slideDown();
            } else {
                $(list).find("li").slideDown();
            }
            return false;
        }).keyup(function () {
            $(this).change();
            if ($(this).val().length) {
                $('.number').hide();
            } else {
                $('.number').show();
            }

        });
    }
    $(function () {
        filterList($("#header"), $("#sortable"));

    });
}(jQuery));

Answer №3

I typically use the keyup event to validate input text. The change event is only triggered after a user finishes typing and exits the input box.

Answer №4

$('.sortable-list').on('focusout', function(){
    var inputLength = $(this).val().length;
    if (inputLength) {
        $('.number-label').css('display', 'none');
    }
    else {
        $('.number-label').show();
    }

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

Is it possible to bind a function to data in Vue js?

Can a function be data bound in Vue? In my template, I am trying something like this: <title> {{nameofFunction()}}</title> However, when I run it, it simply displays 'native function' on the page. Any insights would be appreciated ...

Merge two separate mongodb records

Just getting started with javascript / express / mongodb. For my initial project, I am working on a simple task manager where todos are categorized by priority - "high," "mid," or "low." However, I am facing an issue when trying to display different entri ...

Is there a way for me to update the button text and class to make it toggle-like

Is there a way to switch the button text and class when toggling? Currently, the default settings show a blue button with "Show" text, but upon click it should change to "Hide" with a white button background. <button class="btn exam-int-btn">Show< ...

Tips for resolving vertical alignment styling for images of varying sizes within Vue.js transition-group?

I have created an image slider example, but I'm facing a styling issue when using images of different dimensions. The element leaving the array is positioned absolutely for smooth transitions, but this causes the image to move up. I am trying to vert ...

Inserting HTML content into a DIV with the help of jQuery

Looking for a solution with my index.html file. I want to load other HTML files into a DIV by clicking on buttons. Here's an example of what I'm trying to achieve: I've searched through various examples online, but none seem to work for ...

Is it possible for Vue Router to remember the scroll position on a route and return to the same position when navigating back?

My Vue Router is not saving the scroll position and always loads at the top of the page (0, 0). Any suggestions on what could be causing this issue? Here is my current router code setup: const scrollBehavior = (to, from, savedPosition) => { if (saved ...

Add both single (' ') and double (" ") quotes within the `document.querySelector` code

Given an array of attributes like the following: let elementsArray = [ '[name="country_code"]', '[name="user_tel_code"]', '[name="countryCode"]' ]; If I aim to iterate through them using a ...

I'm attempting to render HTML emails in ReactJS

I have been attempting to display an HTML page in React JS, but I am not achieving the same appearance. Here is the code snippet I used in React JS: <div dangerouslySetInnerHTML={{ __html: data }}/> When executed in regular HTML, the page looks lik ...

Utilize AJAX within an Angular method

I am encountering 2 issues with the $http function in this particular code snippet. $scope.buttonClick = function(){ // Sending input data $.post('lib/add_contact.php', $scope.contact, function(data){ data = angular.fromJ ...

Choose gets stuck while loading an abundance of data using JQuery's .html() and JSON

Here's the code snippet I'm currently using: $.getJSON("registro/backend.php?action=list&id="+sel.value, function(data){ var options = []; for (var i=0; i<data.rows.length; i++) { options += &apos ...

Reviving jQuery Smooth Zoom Pan viewer following container resize

I am in the process of developing a responsive image viewer and have decided to incorporate the Smooth Zoom Pan plugin for enhanced pan/zoom functionality. Within my layout, I have two primary panels: the viewer container and a controls container that are ...

Data loss occurs when the function malfunctions

Currently, I am working with Angular version 11. In my project, I am utilizing a function from a service to fetch data from an API and display it in a table that I created using the ng generate @angular/material:table command. Client Model export interfac ...

What is the best way to fill HTML tables using an ajax response?

This is a Laravel blade view/page that requires updating without the need to refresh the entire page. The blade.php code functions correctly and retrieves data from a MySQL database, but there seems to be an issue with the AJAX and JavaScript implementati ...

What are some ways to optimize Ajax requests for improved speed when multiple identical requests are made on a single webpage?

When the webpage is loaded, a block is dynamically created using an Ajax call to retrieve data from another page. This structure is then populated and added to a specific DOM element. However, multiple Ajax calls during page loads are causing delays. Is ...

Handling JSON Deserialization Error in C# with jQuery and ASMX

Trying to perform an AJAX POST request to a C# ASMX web method, but encountering issues with JSON data deserialization. Despite following the correct steps, I keep getting the error message... {"Message":"Cannot convert object of type \u0027System.St ...

Protractor unable to locate elements using by.repeater

What is the best method for targeting this repeater with Protractor? <a ng-repeat="item in filteredItems = (items | filter:'abc')">{{item}}</a> ...

Extracting CSS from a cell in a Datatable and applying it to other cells within the table

I am currently utilizing the datatables plugin in my project. One of the columns in my table is named "CSS" and it contains CSS code for styling the columns in that row. For example, the table structure in the database looks like this: Name Priority ...

What is the best way to test an externally hosted application with Testacular and AngularJS?

I have a Pyramid app running on http://localhost:6543. This app serves the AngularJS app at /. This app utilizes socket.io. The query is: Can I test this application using these tools? In my scenario.js file, I have the following: beforeEach(function( ...

The placeholder within my input moves up and down when switching the input type from password to text

Currently, I am encountering an issue with the styling of a standard input element in React. Specifically, the placeholder text moves up and down by about 2px when viewed on Chrome, while there are no problems on Safari. How can I go about resolving this i ...

The position of the jQuery VirtualKeyboard is not displaying correctly

I'm currently experiencing an issue with the placement of the keyboard while using the Mottie/Keyboard plugin. The images provided below illustrate my desired outcome and the current behavior: Despite my attempts, the keyboard consistently appears at ...