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

The concatenation of Ajax results appears to append to the existing data

My ajax function handles uploading comments to a form, which then returns the same string. If successful, the comment is added to a comment box and the input text is cleared. The issue arises when a user adds another comment; the new comment is appended w ...

D3 - Rounded edge chart width

Currently facing an issue with the chart where the data value is small, resulting in an 'ear' effect. Can anyone help me with this problem? Below is the code I am currently using: const rx = 30; const ry = 30; svg ...

The flashing of Bootstrap tabs can be seen on various pages

Currently, I am encountering an issue with bootstrap tabs on my website. There seems to be a blinking problem with the tabs on certain pages. Check out this video showcasing the blinking tab in the search result page: Watch Here Interestingly, the same ta ...

Tips for extracting information from a Javascript Prompt Box and transferring it to a PHP variable for storage in an SQL database

My current issue involves a specific function I want my script to perform: before a user rejects an entry on the server side, the system needs to prompt a text box asking for the reason behind the rejection. The inputted reason should then be saved to a My ...

Experiencing issues in retrieving data post-login using ASP.net session key method

I have developed a website using AngularJS for the front-end and Windows webforms for the back-end. I believe that the Authorization process is carried out using ASP.net Session Key. The approach involves creating an AngularJS Post method for "login" foll ...

Bring together the Django blog project with an existing HTML website

My website currently incorporates HTML5, CSS3, JQUERY, and static images. Additionally, I have a Blog created in Django that I would like to seamlessly integrate into the existing website. As a newcomer to Django, I am unsure of the best approach to take ...

Start and Pause PHP Execution on Demand

In order to pause the execution of PHP/HTML code and resume it by clicking on a "continue" button, here is an example: <?php echo "Hello"; // I would like the PHP code to halt after printing "Hello" here. // Additionally, I would like to include a "C ...

Learning about the intricacies of backend Node.js through Angular using GET requests

I am having trouble retrieving the query parameters from a frontend GET request on the backend side. I have attempted to use url and query, but still need assistance fetching the query on the nodejs side. Can someone recommend a method that would allow me ...

Error encountered in TypeScript's Map class

When working with TypeScript, I keep encountering an error message that reads "cannot find name Map." var myMap = new Map(); var keyString = "a string", keyObj = {}, keyFunc = function () {}; // assigning values to keys myMap.set(keyString, "val ...

Why does JavaScript often return the constructor of an object instead of false?

Seeking assistance in resolving issues with the functionality of my script. function CatFactory(cat) // Cat constructor { for (y in cats) { if (cats[y].color == cat.color) {return false;} // return false if already in the array ...

The method I used to position a triangle at the bottom border of a parent element with relative

https://i.stack.imgur.com/RZjJ9.png I am trying to achieve a centered triangle within a border, but I am facing a challenge due to the parent component being relative. When I remove the relative positioning, I struggle to position the triangle in the cent ...

The parameter type 'Event' cannot be assigned to the argument type

edit-category-component.html: <custom-form-category *ngIf="model" [model]="model" (onSaveChanges)="handleChanges($event)"></custom-form-category> <mat-loader *ngIf="!model"></mat-loader> edi ...

What is the best way to invoke a function only once in typescript?

Struggling to implement TypeScript in React Native for fetching an API on screen load? I've been facing a tough time with it, especially when trying to call the function only once without using timeouts. Here's my current approach, but it's ...

What steps should I take to address the issue of sanitizing a potentially harmful URL value that contains a

I've encountered a URL sanitization error in Angular and despite researching various solutions, I have been unable to implement any of them successfully in my specific case. Hence, I am reaching out for assistance. Below is the function causing the i ...

Limiting Firebase queries with startAt and endAt

I need to retrieve the first 100 results from my Firebase data, followed by the next 100, and so on. Despite trying multiple methods, I have not been successful. Method 1 ref.child('products').orderByChild('domain').startAt(0).endAt(1 ...

Seemingly the Tailwind Styles are failing to take effect in my Next.js Project

While following a Next.js tutorial project, I ran into an issue where my project seemed to be way off. It appeared that the tailwind styles were not being applied for some reason, even after tweaking the 'tailwind.config.js' file without success. ...

Ensuring the next tab is not accessible until all fields in the current tab are filled

I am working on a form with a series of questions displayed one at a time, like a slide show. I need help with preventing the user from moving to the next set of questions if there is an empty field in the current set. Below is the script I am using to nav ...

Delivering Access data in HTML format via email

In my MS Access database, I have a report that combines client records from one table (including email addresses) with grouped records fetched from other tables using a Query. I want to send this report directly to each client via email, within the body o ...

Embracing async-await while awaiting events in node.js

I am attempting to incorporate async await into a project that is event-driven, but encountering an error. The specific error message I am receiving is: tmpFile = await readFileAsync('tmp.png'); ^^^^^^^^^^^^^ SyntaxError: Unexpec ...

Turn off the option to select a specific time from the dropdown menu on the datepicker. Additionally, if a particular

I have successfully implemented most of the code I need, but I require assistance with one final aspect. jQuery("#date_num").datepicker({ beforeShowDay: function(d) { var day = d.getDay(); var array = ['28/09/ ...