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

Second image: The suggestion box should disappear upon doing this

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

Rotate each row of the table in sequence with a pause between each flip

I have a table with 3 columns and 10 rows. I would like to flip each row one by one, where each row contains data on both the front and back sides. The flipping animation should be similar to the example provided in this link, but the flipping should sta ...

Tips on correctly determining font size

I'm attempting to style a span element with a specific height (in this case, 23px). However, the browser is automatically adding some extra pixels to the element. There are no additional styles like padding or margin affecting it, just the size of th ...

Using an if statement within a map function in a React component

I am facing a challenge with using an if statement inside a map function without changing the return value. Here is my code snippet: this.example = this.state.data.map((item) => { return( <div> {if(1 + 1 == 2){ dat ...

Unicef's animated web content

Looking to learn more about gate animation and zoom page transition on the Unicef website? I want to incorporate these cool animations into my own project. Can someone provide me with a "keyword" or point me in the right direction to find information on ...

Struggling to retrieve data from AJAX call

I'm having trouble accessing the data returned from a GET AJAX call. The call is successfully retrieving the data, but I am unable to store it in a variable and use it. Although I understand that AJAX calls are asynchronous, I have experimented with ...

Having trouble understanding how to incorporate jQuery GetListItems with SharePoint SOAP - it seems simple, but can't figure it out!

I'm attempting to incorporate a SharePoint list into an Unordered List to set up a basic search function (since Sharepoint's Search functionality is quite lacking). Below is the code I found and adjusted: $(document).ready(function() { v ...

What are your thoughts on the practice of utilizing the useState hook within a component to send data to its parent component?

I have been working on developing an Input component that can be dynamically used in any page to store input values. The component also includes an attribute called getValue, which allows the parent component to access the input value. In my App.js file, I ...

Is there a more effective method for detecting changes in a class variable in JavaScript, aside from using setInterval()?

Is there a more readable way to monitor changes of a class variable from its instance? Although I can use setInterval() to achieve this, the code becomes quite difficult to read. let calibrator = new Calibrator("hardwareName"); calibrator.connect(); let ...

Debugging TypeScript on a Linux environment

Approximately one year ago, there was a discussion regarding this. I am curious to know the current situation in terms of coding and debugging TypeScript on Linux. The Atom TypeScript plugin appears promising, but I have not come across any information ab ...

Having trouble retrieving the chosen option from the select elements

Below is a portion of the code that I have written to capture the selected values of class code and section from a dropdown menu. Currently, only the first element of the select is being retrieved instead of the chosen element. HTML Code: <div id="dia ...

When trying to retrieve a value from a custom render function in React with TypeScript, an error occurs indicating that the value is not assignable to type 'ReactNode'

Recently, I attempted to develop a versatile swiper component using Next.js 13 (App Router) v13.4.12 along with TypeScript. However, I encountered an issue when trying to access data from the component props, which involves a custom function for rendering ...

Error message encountered: "TypeError with jQuery autocomplete and ajax

I can't seem to figure out why I keep encountering this error when trying to set up autocomplete with ajax source. "Uncaught TypeError: Cannot read property 'length' of undefined" Below is the route I have in express. exports.findAllIrds ...

The issue with fetching user profile data on the client-side in Next.js 14

I've run into a problem with client-side data fetching on my Next.js 14 project. More specifically, I'm trying to retrieve user profile information from a backend API using Axios within a component, but for some reason, the data isn't coming ...

Utilizing Vue.js i18n for a multi-line text display

Currently, I am implementing i18n single file component in order to provide translation support for my application. In order to achieve this, I have been utilizing the i18n tag as shown below: <i18n> { "fr": { "text": "Lore ...

Having trouble getting the video to load on your Mozilla Firefox browser?

Unable to play video on Firefox. Error message: URL.createObjectURL(video): Error decoding media resource blob: NS_ERROR_DOM_MEDIA_FATAL_ERR (0x806e0005) Details: Decoder may not support the requested video format with YUV444 chroma subsampling. Tried usi ...

Retrieve the value of the specific element I have entered in the ngFor loop

I've hit a wall after trying numerous solutions. Here is the code I'm working with: HTML: import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styl ...

Once the print dialog is canceled or saved, the current window remains open

Whenever I try to print the data, a new window opens displaying all the respective data of the HTML page. The print dialog then quickly appears, but if I cancel or close the dialog, the current window does not close. Can someone please provide suggestions ...

Validating minimum and maximum values with Angular 2 FormBuilder

I am currently developing a form using Angular 2 Formbuilder and I want to ensure that users can only input positive values into the amount field (with a minValue of 0 and maxValue of 100). How can I go about implementing minimum and maximum value validati ...

Tips for populating class attributes from an Angular model

Suppose there is a Class Vehicle with the following properties: public id: number; public modelId: number; public modelName: string; Now consider we have an object that looks like this {id: 1, modelId: 1, modelName: "4"} What is the best way to assign e ...

How can I implement the ternary operator in React Native and resolve my code issue?

Hello, I'm looking to implement the ternary operator in my code. Specifically, I want to render a FlatList if `cookup` has a value. However, if `cookup` is an empty array, I want to display some text instead. <FlatList data={cookUp} ...