blurring out of an input field and a division element

I am currently working on creating a dropdown suggestion box that hides when the input field and dropdown box are no longer in focus.

My HTML code:

<input type="text" id="user_address">
<div id="user_address_sg">SUGGESTION</div>

<div id="another element">Pressing another element on the page should hide the suggestion box</div>

I have attempted the following:

$('[id=user_address][id=user_address_sg]').focusout(function (){
    $('#user_address_sg').hide();
});

Why isn't the user_address_sg hiding when I select another input field or other elements on the page?

Images (1st: When typing a name, 2nd: Selecting another form while suggestions appear)

First image: The suggestion box should be displayed and clickable

https://i.sstatic.net/UwlFh.png

Second image: The suggestion box should disappear upon doing this

https://i.sstatic.net/60PCo.png

Answer №1

UPDATED: Here is an alternative using CSS:

function provideSuggestion(selection) {
document.getElementById('user_input').value = document.getElementById(selection).innerHTML;  
 }
#user_input_sg {
  vertical-align: top;
  text-decoration: none;
  display: none;
  color:black;  
}

#user_input_sg:focus, #user_input_sg:active {
  display: inline-block;
  color:black;
}

#user_input:focus ~ #user_input_sg {
  display: inline-block;
}
<input type="text" id="user_input">
<a href=# id="user_input_sg">
<span id=opt1 onClick="provideSuggestion('opt1')">OPTION 1</span><br>
<span id=opt2 onClick="provideSuggestion('opt2')">OPTION 2</span><br>
<span id=opt3 onClick="provideSuggestion('opt3')">OPTION 3</span><br>
<span id=opt4 onClick="provideSuggestion('opt4')">OPTION 4</span>
</a>

Answer №2

To ensure proper functionality, it is important to use the blur event and separate the selectors with commas. This is because a single element cannot have two different ids, but two different elements can have different ids. Therefore, it is necessary to separate them like so:

$('[id=user_address],[id=user_address_sg]').blur(function (){
    $('#user_address_sg').hide();
});

For better results, consider using the on() method:

$('[id=user_address],[id=user_address_sg]').on('blur', function (){
    $('#user_address_sg').hide();
});

The blur event occurs when an element loses focus, which seems to be what you are looking for in this case.

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

How can I store the value of `$_POST['data']` in a jQuery variable?

Upon receiving data from a form on a new page, the code looks like this: $id = $_POST['id'] $date = $_POST['date'] The use of jQuery and ajax to process the posted data from the previous page and display it on the current page where ...

Create a copy of a JQuery slider

Hello there, I'm a first time poster but have been reading for a while now. I've been working on creating a simple jQuery Slider and I'm facing an issue... I want to create a slider that utilizes minimal jQuery and can be easily duplicated o ...

Error occurs in ReactJS App when the state is updated in Redux only after dispatching the same action twice

Check out the following code snippet: ChartActions.js import * as types from './ChartTypes.js'; export function chartData(check){ return { type: types.CHART_DATA,check }; } ChartTypes.js export const CHART_DATA = 'CHART_DATA ...

Mobile devices are having issues with CSS rendering

I've encountered an issue with my CSS code. It seems to be working fine until the @max-width:767 media query, but then it stops working on the resolution immediately below it, which is @425. However, it starts working again on resolutions below that. ...

Exploring Angular modules has shed light on a certain behavior that has left me puzzled - specifically, when diving into JavaScript code that includes the

I am currently working with angularjs version 1.4.3 and I find myself puzzled by a certain segment of code in the Jasmine Spec Runner that has been generated. Upon generation, Jasmine (using ChutzPath) creates this particular piece of code: (function ...

Asynchronous Middleware in ExpressJS Routing

I'm having trouble implementing a middleware in Express. Whenever I make a request, I end up with infinite loading times. I've searched on various platforms but couldn't find any examples that utilize an async await middleware stored in a se ...

What is the best way to center-align my list within the designated area?

I need help centering a two column list on my webpage. It's currently justified to the left. How can I adjust it? To see what I'm working with, check out my jsfiddle: http://jsfiddle.net/huskydawgs/c2yqmfzt/5/ <p> A banana is an edible fr ...

Adjusting the array of buttons with various functions within the Header component

I am looking to create a customizable Header component with different sets of buttons that trigger various functions. For example, on the home page, the buttons could be "visit about page" and "trigger vuex action A", while on the about page they could be ...

No reply received on the web browser

I have written a code that is intended to read a JSON file and display it in the browser. The code is functioning correctly as it prints the data to the console, but for some reason, the data is not displaying on the browser. app.post("/uploadfile&q ...

The .val() method is compatible with input fields, but does not work

Having trouble retrieving the value from a textarea input. Switched to an input field and it's working fine. Note: The issue seems to be related to tinyMCE. Removing tinyMCE allows the code to work properly. Any thoughts on this? $('.answer ...

Tips for maintaining the footer at the bottom of the page regardless of the screen size

In my current project, I am dealing with several web pages. For each page, I have arranged three div tags: Header Body (content) Footer The issue arises when it comes to the body div tag, which houses the main content of a page such as forms and descrip ...

Utilize user input to fetch data from an external API

Let's say there is a field for 'part number' input that is not enclosed in a form tag. Whenever a user enters a value, the onblur event or a button positioned next to the input field should trigger a query to an external site via its API and ...

What happens with JQuery if the JQuery IIFE does not get executed properly?

The jquery-3.3.1.js file contains the following code: ( function( global, factory ) { ... } ); Within this Immediately-Invoked Function Expression (IIFE), there is a line allowing for the use of the JQuery and $ variables to call the JQuery function: wi ...

Instructions for integrating AJAX into a PHP script

I am looking to incorporate AJAX into my PHP file so that when I delete an item from a list, the data automatically reloads and the list is updated with the new information. I have created a list of all my data along with a delete button. Below is the PH ...

Several buttons sharing the same class name, however, only the first one is functional

As a newcomer to JavaScript, I am currently working on the front-end of a basic ecommerce page for a personal project. My query pertains to the uniformity of all items being displayed on the page, except for their names. When I click on the "buy" button f ...

Challenges with text in a Bootstrap 5 responsive carousel

I'm currently in the process of developing a new website and I am utilizing bootstrap 5. One issue I have encountered is that the text and button within the carousel in the header section do not appear to be compatible. To provide better clarity, I wi ...

Arranging adjacent div blocks to maintain alignment in a stylish way

I am facing an issue with divs that are placed side by side inside a table. These divs have been styled to appear as colored blocks. Everything seems fine when the text within each div fits on two lines, however, if it overflows onto another line, the en ...

Turn off jQuery autocomplete box

I have a simple query - how can I turn off the dropdown feature of jQuery Autocomplete? My goal is to trigger my own function when the user begins typing, and I prefer not to display any additional content. Below is what I currently have: $( ...

Can anyone please guide me on how to extract the IP address of a specific individual using Node.js?

There's an individual running some kind of exploit scanner on my server. I'm receiving strange requests like: IP ADDRESS: ::ffff:127.0.0.1 www-0 (out): POST /cgi-bin/php5?%2D%64+%61%6C%6C%6F%77%5F%75%72%6C%5F%69%6E%63%6C%75%64%65%3D%6F%6E+%2D%64 ...

Apple's iPhone does not adhere to media query specifications

My responsive website was functioning perfectly on desktop, Android, and Windows Phone devices. However, when I asked my friends to check it on their iPhones running iOS 10, they informed me that the media queries were being ignored on iPhone models 5, 5s, ...