Trick for hiding CSS elements when input field is vacant

Is there a way to hide the search result when the input is empty?

While everything is functioning correctly, I would like to prevent the search result from remaining visible after clearing the input field. For example, if you type 'A' and then delete it, the result should disappear.

A big thank you to anyone who can provide the solution!

The element

<div id="result"></div>
is the one that needs to be hidden.

This is the CSS code for my search implementation:

.content{
    width:275px;
}
#searchid
{
    width:275px;
    border:solid 1px #000;
    padding:10px;
    font-size:14px;
    border-radius:5px;
    -moz-border-radius:5px;
    -webkit-border-radius:5px;
}
#result
{
    position: absolute;
    width:275px;
    padding:10px;
    display:none;
    border-top:0px;
    overflow:hidden;
    border:1px #CCC solid;
    background-color: white;
}
.show
{
    padding:10px;
    border-bottom:1px #999 dashed;
    font-size:15px;
    height:50px;
}
.show:hover
{
    background:lightgrey;
    color:#FFF;
    cursor:pointer;
}

Here's the HTML code for the search input box:

<div class="content">
                        <input type="text" class="search" id="searchid" placeholder="Search"/>
                        <div id="result"></div>
                    </div>

This is how my search results are displayed:

<div class="show" align="left">
                           <span class="name"><a href="/sheridan/page/?p=' .  $rowsTitle['id'] . '">' . $rowsTitle['title'] . '</a> ' . $label . "<br>".
                      </div>

Below is the JQuery script used to retrieve search information:

$(function(){
        $(".search").keyup(function()
        {
            var searchid = $(this).val();
            var dataString = 'search='+ searchid;
            if(searchid!='')
            {
                $.ajax({
                    type: "GET",
                    url: "/sheridan/script/search.php",
                    data: dataString,
                    cache: false,
                    success: function(html)
                    {
                        $("#result").html(html).show();
                    }

                });
            }return false;
        });

        jQuery("#result").live("click",function(e){
            var $clicked = $(e.target);
            var $name = $clicked.find('.name').html();
            var decoded = $("<div/>").html($name).text();
            $('#searchid').val(decoded);
        });
        jQuery(document).live("click", function(e) {
            var $clicked = $(e.target);
            if (! $clicked.hasClass("search")){
                jQuery("#result").fadeOut();
            }
        });
        $('#searchid').click(function(){
            jQuery("#result").fadeIn();
        });
    });

Note: I unintentionally omitted the JQuery function used to extract information from the database in the earlier explanation.

Answer №1

Instead of clearing the result div, it remains filled with data when there is a letter present.

$(".search").on("keyup", function(){
    if($(this).val()==""){
        $("#result").hide();
    }
    else {
        $("#result").show();
    }
});

Link to Fiddle

Answer №2

In order to accomplish this task, JavaScript must be utilized since CSS does not offer a method for recognizing empty input fields.

For the demonstration below, I have opted to utilize jQuery; however, it can also be done without any external frameworks.

$('.search').on('input', function() {
    $('#result').toggle( $(this).val() );
});

JSFiddle Example

Answer №3

Implement JQuery for user interaction.

$( "#searchid" ).keypress(function() {
  var searchValue = $( "#searchid" ).val();
if(searchValue == '') {
  $("#result").html('');
}
});

Answer №4

Check out the code below:

$(document).ready(function(){
  $("#searchid").keypress(function(){
    var len = $("#searchid").val().length;
     if (len <= 0)
     {
         //clear the result
        $("#result").hide();
     }
  });
});

update:

try using $("#result").hide();

or

$("#result").css("display","none");

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

What is the best way to align the 'Typography' component in the center?

Attempting to center it using flexbox with justify-content did not yield the desired result. I also tried replacing the Typography component with a div tag, but still no success. import {AppBar,Zoom,Toolbar,Typography,CssBaseline,useScrollTrigger,Fab,ma ...

Example using three.js showing issues with external resources failing to load on jsfiddle.net

Currently, I am endeavoring to make progress with this sample project: github.com/josdirksen/learning-threejs/blob/master/chapter-09/07-first-person-camera.html I have made attempts at replicating the code on my personal pages.github.io account and also m ...

Utilizing HTML's multiple input type color feature to save selected colors directly to the database

I am currently using the input type color to select colors for customizing my site. I save the selected color to a database and then retrieve it to apply it to different areas of the site. This works well for a single input type color, but now I have mul ...

Unusual sequence of JQuery Ajax calls

Within my website, there is a project div that is displayed using EJS. The data for the projects in EJS are rendered using a forEach loop, resulting in multiple similar divs appearing on the page. Each project div is assigned an id for identification pur ...

I am noticing that my popover is causing my page to shift when I click it. It is expanding the width of my page more than I would

Upon clicking the user id popover on my page, it expands the page width instead of adjusting within the page boundaries. This is the issue: https://i.stack.imgur.com/EqaMo.png There's a small white space present that I want to eliminate. When the po ...

What is the reason behind the label value persistently showing up after the page is refreshed?

Why is the data that I deleted from the database still showing in the label? Even after running the delete function and reloading the page. The label should not have any value once the data is deleted. Here is my code: $(document).on('click', ...

Enter the [color] HTML5 code and check for compatibility with all the latest web browsers

I am interested in implementing a color picker functionality using the input[color] element in HTML5. I would like to confirm if this method is compatible with all modern browsers. Additionally, I am curious if there are alternative ways to achieve this, ...

Guidance on implementing fallback font formats using FontFace API

I am exploring the FontFace API (not @fontface) and wondering if there is an easy way to include multiple font formats, similar to providing multiple sources in @fontface. Alternatively, is there a simple method to identify which font formats are supporte ...

Tips for Updating HTML Table Content Dynamically Using JavaScript without jQuery

I am in the process of developing a web application that requires me to dynamically change the content of an HTML table based on user input, all without relying on jQuery or any other external libraries. Adding rows to the table is not an issue for me, but ...

What is the best way to define the width of text inside a div block?

I'm having trouble adjusting the width of the text in my code to only fill 80% of the body element. I've tried using both the width property and padding, but neither seems to be working for me at the moment. Here's the HTML: <body&g ...

Comparison between Mobile Phone's innerWidth and innerHeight Versus Resolution

My test phone, the Galaxy S3 Mini, has a resolution of 800x480 according to its specs. Strangely, when I run the following code in my HTML game: window.innerWidth window.innerHeight The width appears as 533 and the height as 295. I recently discovered ...

Having trouble with jquery's empty() function not functioning as expected

I'm brand new to using jquery so I apologize in advance for any beginner mistakes. Essentially, my issue is straightforward: Here is the HTML code I have: <div class="v" align="center" id="div4"> <div id="div5" class="h blurb"> <sp ...

Designing my website to resize and adapt to different screen resolutions using CSS

As I navigate my first week of CSS, HTML, and PHP programming, I encountered a problem with text overlapping and causing issues on my site when scaled according to window size. I'm seeking clarity on what mistakes I may be making. Despite trying medi ...

The gaps separating rows

I'm struggling with getting my divs to look like a table, especially when it comes to highlighting a selected row. I've tried adjusting padding and margins without success. Does anyone have any suggestions on how I can achieve this effect? .ta ...

Issue with distinguishing JavaScript code from an SVG file

Seeking assistance as I have an SVG file that is mostly composed of a script. My goal is to separate the script for compression purposes, but I am struggling to find a way to achieve this. Any guidance or help on this matter would be greatly appreciated. ...

Guide on how to display matching options in an input box using HTML datalist based on user input at the beginning

I am a beginner in React and I am looking to create an autocomplete suggestion box for a text input field. I want the suggestions to only match the first letters of the available options, unlike the current behavior of HTML's <datalist>. Althou ...

Issue with custom page not displaying summary image in Moodle

Whenever I try to fetch a summary image on my customized page, it does not show the image's name and instead displays a small icon image. echo format_text($course->summary); Click here for an example image ...

Having trouble connecting a JavaScript file from my local directory to an HTML document. However, when I try to access it in the browser, I keep getting

Currently, I am attempting to connect a javascript file to my html document. Following the directions at this link, I am trying to enable the selection of multiple dates from a calendar as input in a form. The instructions mention that I need to include ...

Troubleshooting Issue with Nested ng-include in AngularJS: Difficulty arises when the parent element with the ng-include attribute is dynamically added using the ng-

Click here to see a demo plunker that will help you understand my issue. On my main page, I have a table. Each table row is followed by a hidden empty row. When the first row is clicked, I use a directive to inject HTML into the empty row below it. Main ...

Glitchy/Crazy CSS3 Animations

Currently, I am developing a website at . One of the features I have implemented is CSS3 transitions for route changes, but this feature only works in Chrome. Here's how the animation works: I apply the .preanimate class to rotate the phasing out di ...