Display the X button solely once text has been inputted into the textbox

I have integrated a text clearing plugin from here in my project to allow users to clear the input field by clicking on an X button. However, I want to modify the code so that the X button only appears when there is text entered in the textbox. I attempted to set a condition in the JavaScript code using the return statement:

if ($('#search').val().length != 0)
but it did not yield the desired results. Below is the snippet of code I tried:

$(document).ready(function(){
    if ($('#search').val().length != 0){
        $('#search').clearable();
        $('.divclearable').show();
    }
    else{
        $('.divclearable').hide();
    }
});

Your assistance with this issue would be greatly appreciated.

Answer №1

Implement a listener for the keyup event -

$(function () {
    $("#search").on("keyup", function() {
        if ($('#search').val().length != 0){
            $('#search').clearable();
            $('.divclearable').show();
        }
        else{
            $('.divclearable').hide();
        }
    });
});

Answer №2

Upon examining the CSS, it is evident that the button belongs to the clearlink class.

To hide it, you can simply use $("a.clearlink").hide().

This method caters to events beyond basic key presses:

$('.divclearable > input').change(
    function() 
    {
        if($(this).val().length == 0)
           $(this).closest('a.clearlink').hide();
        else
           $(this).closest('a.clearlink').show();
    }
);

Answer №3

Is it possible for the jquery change event to trigger when javascript changes an element's text?

To ensure that the clear button both hides and clears text, consider adding a click event. However, be cautious of potential conflicts with the library you are using.

$("#search").change(check_input);
$('.divclearable').click(check_input);
check_input = function(){
    if ($('#search').val().length != 0){
        $('#search').clearable();
        $('.divclearable').show();
    }
    else{
        $('.divclearable').hide();
    }
};

Answer №4

Let's discuss the logic, but remember, you'll need to implement it yourself: There's a CSS class known as "clearlink" which shows the close button. You can customize it by setting one of the initial values to be: display: none. Then, in your JQuery code, when you detect a length change, use a method to change display: none to block. Alternatively, you could create a copy of clearlink called clearlink1 and change the class name of the element.

You can easily do this by using the Inspect Element feature in your browser.

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

Auto language-switch on page load

Wondering if using jQuery is the best approach to create a single French page on my predominantly English website. I want it to work across multiple browsers on pageload, currently using HTML replace. jQuery(function($) { $("body").children().each(funct ...

Switch between toggling tasks in Vue does not seem to be functioning as

I'm reaching out again because I'm struggling to figure out what I'm doing wrong. I followed a tutorial step by step but the code isn't working as expected. My goal is to toggle between marking tasks as done and not done. When I test th ...

Utilizing dotenv: Incorporating the value of one environment variable into the name and value of another environment variable

When it comes to my testing framework, I rely on dotenv for handling environment variables across different test environments. Currenty, I'm looking for a way to incorporate the value of a specific environment variable into both the value and name of ...

execute the middleware function within the router

I've integrated sessions in my express.js application using Mozilla's client-sessions and I'm encountering an issue. My post and get requests are in router.js, while the middleware is in app.js. When I try to run it, I receive the following ...

Unable to make changes to a file authored by a different user within Firestore using Vue.js / Firestore

I appreciate any assistance in advance, as this issue has been causing me a lot of frustration! Currently, I am adhering to the firestore data model where users are able to create their own documents associated with their userID. This ensures that users c ...

What is the jQuery plugin that can search for elements and display them in real-time within a DIV?

Currently, I am in search of a jQuery plugin that can assist me with the following: Ability to have an input field for user search text Search through my elements and display only those that match the search string entered by the user. Essentially creati ...

Tips for handling null input values when saving to a database

<!DOCTYPE html> <html> <head> <title>Data</title> </head> <body> /* Enter your data here */ <form action="this.php" method="post"> <input type='text&a ...

JavaScript Regular Expression that identifies commas enclosed within quotation marks

I am attempting to parse a text-based log file in the following format: type: 'click', category: 'REFRESH_DOOR', desc: 'clicked refresh from door 0124', site: 'mysite', pathname: '/load_areas/all/doors&apos ...

Extract information from a string to retrieve the array specifications

After making a request to the server, I received the following response: { "statusCode": 200, "body": "{\"Errors\":\"\",\"Message\":\"\",\"Output\":\"\",\"TokenID\":\"F10645774 ...

I'm curious why one of my Material UI autocomplete components is displaying options with a blue background while the other isn't. Take a look at the code sandbox for more insight

UPDATE: Problem solved! I managed to find a solution and have updated my sandbox with the fix! REVISION: After some investigation, I have identified that the issue lies within this specific line of code in the autocomplete... isOptionEqualToValue={(option ...

How come certain jQuery scripts and icons are not functioning properly after the partial view is loaded in ASP.NET Core?

I am encountering an issue on my page where I have a list of information that can be searched using fields and Ajax. When I reload the information as a partial view, none of the jQuery code seems to work after the reload. What could be causing this problem ...

Having trouble clearing the interval after setting it?

I developed a slideshow script called function slide(). The intention is for this function to begin when the 'play' button is clicked and pause when the 'pause' button is clicked. I implemented setinterval and it functions properly, how ...

Leveraging TYPO3 Fluid for dynamic template rendering

I am currently developing an extension using EXTbase and fluid for TYPO3 v7+. I have encountered a situation where I need to render my fluid templates based on certain controller conditions. Under a specific condition, I want to include HTML code from a us ...

Difficulty arises when attempting to run code when a checkbox is not selected

In my form validation process, I am facing an issue where I need to validate certain values only if a checkbox is unchecked. If the checkbox is checked, I want to use the values that were previously added. However, none of the existing code snippets seem t ...

Transforming control of execution seamlessly between two interactive functions in nodejs

Two functions are used to take input from the CLI using process.stdin. The issue arises when one function is done taking input, as a similar function is called. However, while the control shifts to the second function, the first function continues executin ...

Is there a way to manipulate the placement of an image within a div using CSS?

Teaching myself HTML has been quite the journey. Right now, I'm in the process of building a website purely for its aesthetic appeal, and I seem to be hitting a roadblock with the CSS/div element. As of now, it appears like this. When the h1 is remove ...

Using a prop array as v-model in a Vue JS CheckBoxGroup implementation

Struggling to create a reusable CheckBoxGroup component with a prop array as v-model. I checked out the vuejs guide at https://v2.vuejs.org/v2/guide/forms.html#Checkbox which uses the v-model array in the data of the same component. However, this approach ...

What is the best way to automatically close a parent popup window when the child popup is

Currently, I am developing a web application using Angular that requires managing nested popups. Specifically, in my scenario, I initiate Popup 1 and from within that popup, I trigger another popup (Popup 2) upon clicking "delete." My goal is to ensure tha ...

What is the process for uploading files using AngularFire on Firebase Storage?

Despite watching multiple videos and tutorials, I am encountering a 403 error while working with Angular 1. To solve the issue of ng-model not supporting files, I created an Angular directive named file-model: app.directive('fileModel',['$ ...

Ways to modify the source of images that do not possess a class or ID using JavaScript

I'm struggling to change the source of the img element using JavaScript and Ajax. The img tag doesn't have any IDs or classes, making it difficult for me to select and update the src. Can anyone provide guidance on how I can accomplish this? Belo ...