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

Is there a way to use HTML and JS to draw custom lines connecting elements?

Sorry if this question has been asked before. Is there a way to create straight lines connecting HTML elements with just HTML and JavaScript, without relying on SVG or Canvas? If so, what would be the most effective approach? ...

What is the reasoning behind jQuery UI employing CSS classes as opposed to pseudo-classes?

In this detailed explanation found on this website, it is discussed why jQuery UI uses CSS classes like .ui-state-active that are applied through JavaScript, rather than utilizing existing CSS pseudo-classes like :active. What is the reasoning behind thi ...

How can I arrange a table in Angular by the value of a specific cell?

Here's the current layout of my table: Status Draft Pending Complete I'm looking for a way to sort these rows based on their values. The code snippet I've been using only allows sorting by clicking on the status header: onCh ...

Avoiding text from overflowing a DIV when the parent DIV's width is specified as a percentage

After extensively searching through over 20 similar posts, I have not been able to find a solution that works for my specific issue. The layout of some content I'm working with resembles the example provided here: Check out the Fiddle Example In th ...

Apps created with PhoneGap will maintain the original sizing of web pages and not automatically resize for display on Android devices

After successfully porting my web-based tool to Android using PhoneGap from my Github repository, I encountered an issue with the display on Android devices. The app loads up too big for the screen, forcing me to constantly scroll around to see and access ...

My Django function doesn't get triggered by the form submission using post method

I'm facing a frustrating dilemma and issue. Currently, I am working on a form written in HTML using Django, which is meant to update information in my database related to the specific page it is on. The problem lies in the fact that the Django termi ...

HTML5, canvas covering every element

Below is the code that I am working with: <html> <head> <title>canvas</title> </head> <body> <canvas width="1745" height="569" style="width: 1730px; height: 1680px; position: absolute; z-index: 1"></canvas> ...

Shifted picture next to the accompanying words

I have successfully created a slideshow of images using JavaScript. <html> <head> <script language="JavaScript"> var i = 0; var path = new Array(); path[0] = "one.jpg"; path[1] = "two.jpg"; function swapImage() { document.slide ...

a new webpage beginning from a different location

Starting from scratch here, I must apologize for not providing any code upfront. The issue at hand is this - I've got a page full of information sorted by ID (retrieved from the database). These IDs are linked from another page where users can click ...

Creating a dynamic background using a blend of two hues in CSS

Is there a way to stack two colors on top of each other using just one div element, or even better, achieve the same effect with just one color that is a blend of the two? I currently have two divs superimposed, with the top one at 60% opacity. I've ...

What is the best way to iterate through multiple iframes?

I need help figuring out how to load one iframe while having the next one in line to be displayed. Is there a way to create a script that cycles through multiple iframes after a certain amount of time? ...

Alignment in rows with a flexible number of rows

My goal is to create a series of equally sized elements with consistent spacing. I want these elements to be evenly distributed both horizontally and vertically on the page, adjusting accordingly to changes in screen size or number of elements. The challen ...

Automatic table width expansion with CSS

I'm in the process of creating a new website, and I want the layout to resemble the following: +---+--------------+ |# | | |n | #page | |a | table.basic | |i | | |g | | |a | | |t | ...

Step-by-step guide on resolving the issue of an ajax form redirecting to a mailer

I have been working on implementing the contact form on an HTML page. The validation was functioning correctly until I added it, and now the form is no longer submitting properly. Despite this issue, the page still redirects to mailer.php. The AJAX functio ...

Press the button to update several span elements

Imagine I have multiple span elements like this: <span>A</span> <span>B</span> <span>C</span> <span>D</span> and a div element (which will be converted to a button later) named "change". <div id="chan ...

Having issues with CSS vertical margin not functioning properly

#outline { background: green; height: 96vh; width: 96vh; } #box { background: white; height: 86vh; width: 86vh; margin: 5vh; border: 1px solid #DDDDDD; overflow: hidden; } <div id="outlin ...

What is the best way to load my CSS file using express.static?

How do I properly load my CSS file using express.static in Node.js? I have attempted various methods to link my stylesheet to my HTML file through Express, and I'm also interested in learning how to include images, JavaScript, and other assets to crea ...

Having difficulty altering the font in the WordPress tinymce editor

I've been attempting to update the font in the WordPress tinymce editor, but I'm running into issues. First, I created a tinymce-custom-editor.css file with the following code: @import url(https://fonts.googleapis.com/css?family=Open+Sans:400,7 ...

Utilize Google Maps to receive directions to a specific destination and discover current traffic conditions along the route using their comprehensive API

I am currently working on implementing the Google Maps direction identifier functionality with traffic details. However, I am able to obtain directions but not specific traffic details for a selected path; it seems to apply overall traffic data instead. ...

Unable to transmit HTML emails

I've been encountering an issue while trying to send HTML emails using Gmail SMTP from CI. It seems that my emails are being rejected if they contain any tables. Interestingly, there is no error message provided; the emails simply do not show up in my ...