Having trouble with the focusout() function not registering on the search box?

When using the focusout function, I encountered an issue where clicking on a title in the search results would prevent redirecting to the title page. Although the function worked properly when closing the search results by clicking on a different element on the page, the results also closed when clicked on.

I attempted using the blur function as well as hide() and show(), but the outcome remained the same. Even though I have set .result display to none, it should not hinder me from selecting a search result. What could be causing this issue?

// jquery.js

$(document).ready(function() {
  $('.search-box input[type="text"]').on("keyup input", function() {
    /* Get input value on change */
    var inputVal = $(this).val();
    var resultDropdown = $(this).siblings(".result");
    if (inputVal.length) {
      $.get("includes/searchbar.inc.php", {
        term: inputVal
      }).done(function(data) {
        // Display the returned data in browser
        resultDropdown.html(data);
        $('.result').css('display', 'block');

        $("#searchboxy").focusout(function() {
          $('.result').css('display', 'none');
        });
        $("#searchboxy").focusin(function() {
          $('.result').css('display', 'block');
        });

      });
    } else {
      resultDropdown.empty();

    }
  });

  // Set search input value on click of result item
  $(document).on("click", ".result", function() {
    $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
    $(this).parent(".result").empty();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- header.php -->

<div class="search-box" id="searchboxy">
  <input type="text" autocomplete="off" placeholder="Search for a game or genre..." />
  <div class="result" id="resultsearch"></div>
</div>

Answer №1

The issue with your code was the focusout event handler triggering every time the search input lost focus, including when clicking on the results.

This caused the click event on the results to be triggered after the hide action in the first handler, preventing it from working as intended.

To address this, a better approach is to attach a click event handler to the entire document and check if the clicked element has the parent #searchboxy. If it does, hide the results; otherwise, leave them visible.

In the demo, I simulated a custom result from your API without clear data, which you displayed without manipulation.

I also revised how you captured click events on the result items by attaching the event handler once to the parent results.

// Your fetch replaced with an unreachable URL
const makeSearch = (term) => {
  return new Promise((resolve, reject) => {
    resolve(`
      <ul>
        <li>Result1</li>
        <li>Result2</li>
        <li>Result3</li>
      </ul>`
    );    
  });
}

// Click event on the document
$(document).on('click', function(event){  
  // Hide .result if clicked element doesn't belong to #searchboxy group
  if(!event.target.closest('#searchboxy')){
    $('.result').css('display', 'none');
  }
});

// Show .result on input text focusin
$("#searchboxy").on('focusin', function() {      
  $('.result').css('display', 'block');
});

// Click event on .result box...
$(document).on("click", ".result", function(event) {  
  const textOfClickedResultElement = event.target.innerText;  
  $(this).parents(".search-box").find('input[type="text"]').val(textOfClickedResultElement);
  $(this).parent(".result").empty();
});

$(document).ready(function() {

  $('.search-box input[type="text"]').on("keyup input", function() {
    /* Get input value on change */
    var inputVal = $(this).val();
    var resultDropdown = $(this).siblings(".result");
    if (inputVal.length) {
      
      //$.get("includes/searchbar.inc.php", {
      //  term: inputVal
      //})
      
      // Replaced search request for demo purposes
      makeSearch(inputVal)
        .then(function(data) {          
          // Display returned data in browser
          resultDropdown.html(data);
          $('.result').css('display', 'block');
        });
    } else {
      resultDropdown.empty();
    }
  });
  
});
.info{
  margin-bottom: 10px;
}

#searchboxy{
  border: dashed 3px lightgray;
  padding: 10px 10px;
}

#searchboxy input{
  width: 15rem;
}

#resultsearch{
  border: solid 1px gray;
  display: none;
  margin-top: 1rem;
}

#resultsearch li{
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="info">
  Start typing inside the textbox to show the search results.<br>
  Clicking anywhere outside the dashed borders will hide the results.<br>
  Giving focus to the textbox will show the results.<br>
  Clicking any single result item will push its value into the search box.
</div>

<div class="search-box" id="searchboxy">
  <input type="text" autocomplete="off" placeholder="Search for a game or genre..." />
  <div class="result" id="resultsearch"></div>
</div>

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 CSS styling for the <body> element is not rendering the expected results

website <!DOCTYPE html> <html> <head> <title>Time Tracker</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link ...

Tips on preventing a nested loop's inner ng-repeat from updating when the array undergoes changes

My current challenge involves working with an array of events, each event has teams participating in it. Although these objects are related, they are not properties of each other. I am attempting to loop through every event and display the teams participa ...

Disable the ng-change event

Is there a way to prevent the ng-change event from happening? I have a select box with an option that I don't want users to select. Instead, I want to display a warning message and then revert back to the previously selected option. To achieve this, ...

Pause animation when hovering over their current positions

I am working on a project with two separate divs, each containing a circle and a smiley face. The innercircle1 div is currently rotating with a predefined animation. My goal is to create an effect where hovering over the innercircle1 div will pause its rot ...

How can a JQuery ajax success function access the parent object it resides in?

The following is a snippet of my JavaScript code: function Dog() { this.bark = function() { // bark }; $.ajax( perform AJAX call, upon success execute: this.bark(); ); } var TopDog = new Dog(); Unfortunately, the above script doesn't work a ...

What is the best way to handle multiple JSON data using jQuery?

Understanding how to utilize jquery for parsing simple json is a valuable skill. json { "Symbol": "AAL.L", "Name": "ANGLO AMERICAN", "Last": "3061.50", "Date": "7/26/2011", "Time": "11:35am", "Change": "+3 ...

Button missing post ajax loading

I've encountered a problem with my code that populates a table and contains buttons, which trigger an AJAX load. The content is loaded into a DIV with the ID 'DIV1', but when I try to access the buttons in that DIV1 by clicking on them, they ...

The function addClass() seems to be malfunctioning

I'm currently experimenting with creating a scrolling cursor effect on a string of text. The goal is to make it look like the text has been highlighted with a blinking cursor, similar to what you see in your browser's search bar. window.setInter ...

Rendering Local HTML with local styling and scripts in React Native Webview

I am having trouble loading a local HTML, CSS, and JS file in my React Native webview. The CSS is not being applied to the HTML. Here is my folder structure: My HTML file, along with CSS, images, and JS file are all placed in the following app folder stru ...

Changing the value of an input in an HTML response received through an AJAX request

Is there a way to set the value of an input (retrieved via an ajax call) before adding it to the document? $(function () { $("#addItem").click(function () { var numRows = $('.row').length; $.ajax({ url: this.href ...

What is the best method for positioning two forms in a vertical arrangement?

I'm looking to integrate a Login form in HTML within my C# project. Here's what I have so far: However, as you can see, the layout is not very aesthetically pleasing. I'm struggling to align the elements in a more visually appealing way. My ...

Text randomly appears on the html page

I've been dedicating a significant amount of time to finding a solution, but haven't had any luck. I'm aiming to create a visual effect where 10 words with varying font sizes slide in from different directions on a canvas within my document ...

Innovative approach to implement dynamic datepicker using jQuery

I am trying to dynamically give a date format using jQuery UI, but I am facing some issues. Here is my code: <table id="sample"> <tr> <td> Date </td> </tr> In my JavaScript file: $("#datepicker").datepicker ...

Imagine a scenario where clicking on an image causes it to be rotated or

Could use some assistance figuring out what's missing here. I've added a random photo from Wiki, similar in size to the images I'll be working with. The images will vary in size, but I want them to always remain visible within the browser w ...

What is the best way to update the content of a modal using jQuery and AJAX?

Despite previous inquiries on this matter, none of the answers provided have been helpful to me. Therefore, I am addressing the issue again... I am currently developing the frontend of a website that does not involve any backend functionality (no server c ...

Converting a webpage into UTF-8 format

Can you explain the concept of encoding a webpage to me? When someone mentions that a page is encoded in UTF-8 or another format like EUC-KR, what does that signify? Does it pertain to encoding done on the server-side or client-side? Is it related to th ...

Ways to implement the tabIndex attribute in JSX

As per the guidelines provided in the react documentation, this code snippet is expected to function properly. <div tabIndex="0"></div> However, upon testing it myself, I encountered an issue where the input was not working as intended and ...

Guidelines for comparing two distinct dates using jQuery

const currentDate = $("#date").text(); // the current date is set as a variable 01/06/2017 // Another date is declared as a variable let startDate = '01 / 06 / 2017'; if (currentDate == startDate) {} if (currentDate < startDate) {} <script ...

Avoiding the default action and using a false return value do not produce the

Despite trying preventDefault, return false, and stopImmediatePropagation, the page continues to redirect back to the first selection instead of redirecting to the textarea after inputting all required fields and clicking on the button. The issue persists ...

Initiate the AJAX call when the page is loaded

I want the AJAX request to load automatically when the page loads. Currently, I have to refresh the page for it to be loaded. Here is the updated code snippet: $(document).on("pageinit", "#members", function() { $.ajax({ url: 'data.php', succe ...