Show the national flag in the search bar only once the specific country has been chosen

I am developing a unique custom dropdown feature for selecting countries. Here are the specific requirements:

Requirement 1: The dropdown should populate with countries whose names start with the letter typed in the search box.

Requirement 2: Clicking on a country name in the dropdown should mark it as active.

Requirement 3: Display the flag of the selected country on the right side of the search box.

I have successfully implemented the auto-population feature and need assistance with the remaining functionalities.

function autocomplete(inp, arr) {
  /*the autocomplete function takes two arguments,
...
});

/*An array containing all the country names in the world:*/
var countries = ["Afghanistan","Albania","Algeria", ... "Zambia","Zimbabwe"];

/*Initialize the autocomplete function on the "myInput" element with the countries array as possible values:*/
autocomplete(document.getElementById("myInput"), countries);
...

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

Answer №1

I have integrated it into my code snippet. To make the code functional, you need to toggle the display property of the image. Display the image when a valid input is entered, and hide it otherwise.

To achieve this, add a class called hide to your image container:

<div class="col-2 cunt-flg hide" align="">
  <img src="Australia.png" class="cunt-flg-img" >
</div>

Assign the following property to this class:

.hide {
  display: none;
}

Use JavaScript for toggling purposes.

let image = document.querySelector('.cunt-flg')

// Inside the input eventListener handler

// If the input is empty, hide the flag
if (!val) { image.classList.add('hide'); return false;} 

// Show the image when there is a valid input (after the autocomplete list closes)
image.classList.remove('hide')

This is how it appears:

[JavaScript code snippet]
[CSS styles snippet]
[HTML code snippet]

Edit:

To change the flag corresponding to each country, ensure consistent naming and file type across all flag images (.png/.jpeg). Use a uniform naming convention like countryName.png.

In the <img> tag, dynamically set the src attribute using JavaScript based on the country name:

const img = document.querySelector('.cunt-flg-img')
img.src = val + ".png"

// If the images are stored in a different folder
img.src = "folder-name/" + val + ".png"

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 directive in an ionicModal is executed first, even before the controller is fully loaded

I recently encountered a challenge with a $ionicModal containing a directive called <scrap-link-cards>, which accepts a two-way binding scope object. This directive is included in the $ionicModal template: <scrap-link-cards datasource=(updates.up ...

Significance of using 'abort' mode in JavaScript Ajax call

I'm a bit confused about the 'abort' option in JQ Ajax requests. Can someone explain its purpose? $.ajax({ **mode: 'abort',** dataType: 'html', url: baseUrl + '/books ...

What's the best way to eliminate blank space in my Bootstrap grid columns?

I'm facing an issue with the search filter layout on my website. It includes input fields for a search term, two datepickers, and two buttons: <div id="search-holder"> <div id="search-box"> <div ...

Does __ only function with curried functions as intended? What is the reason for it working in this case?

I'm trying to figure out the reason behind the successful usage of __ in this particular code snippet : function editAddress (id, addressId, model) { return BusinessService .getById(id) .then(unless( () => checkUrlValue(add ...

Determine the difference in time

There are two input types for time: 1. Time of entry. 2. Time of exit. For example: Start: 00:00 End: 01:30 Result: 1.5 Start: 14:00 End: 00:00 Result: 10 An algorithm needs to be created to calculate the number of employees working at a given time. Th ...

What is the best way to employ a Node.js server for uninterrupted delivery of array updates to localhost?

My current approach involves creating an empty array, extracting the value associated with the first name key from a separate object, sending it to localhost through a Node.js server, iterating back to access new data from another object and adding it to t ...

I keep getting an error message that says "The JSX element type does not have any construct or call signatures."

I am currently developing an application that takes user input through buttons and creates an array. However, when I attempt to display the array, I encounter a JSX element type error. import { Delete } from "lucide-react" export function Passwo ...

Dynamic updating of Rails 3.2 webpage elements with the help of JavaScript

Currently, I have implemented a display view that utilizes the app.js file. The data is retrieved from the database and displayed using an API in the app.js file. I am looking to automatically refresh the display every 5 seconds without having the entire ...

The second entry is not being styled by CSS, is there an issue with the code in this section?

I am facing a challenge while trying to set the same background image for two div elements: .abc { background: url('images/autogen.png') no-repeat 0px -133px; width: 256px; height: 256px; }; .def { background: url('images/autogen.png' ...

PWA notifications not working on iOS with FCM even after multiple tries

I am currently utilizing Firebase Cloud Messaging in order to send daily notifications to iOS users who have installed a PWA app. Upon testing, I noticed that each token is limited to receiving only 2 notifications successfully. Any attempt beyond that w ...

How about utilizing node.js as a peer for WebRTC?

Are there any available modules for utilizing node.js as a peer in WebRTC? I am interested in using WebRTC in a client/server manner rather than P2P for its ability to send packets unreliably (i.e. avoiding the delay caused by TCP's guarantee of packe ...

typescript error caused by NaN

Apologies for the repetitive question, but I am really struggling to find a solution. I am facing an issue with this calculation. The parameters a to g represent the values of my input from the HTML. I need to use these values to calculate a sum. When I tr ...

Unable to attach numerous parameters to the content of the request

I am encountering an issue with my code where I have two classes and need to call two separate models using two store procedures to insert data into both tables. The controller is set up like this: [HttpPost] public IHttpActionResult AddData([FromBody]ILi ...

Get rid of the standard shadow located on the bottom and right of the input text field

My input fields have some border rounding and are displaying an unwanted shadow on the right and bottom. I've tried using the box-shadow property to control the width, color, and other properties of the shadow, but it's not working as expected. H ...

Extract JSON content from an array's values containing underscores

I am currently working with an array of objects and need to implement a filter on it. The objects in the list contain an owner_id property within the JSON... Currently, I am looping through all the items in the array. However, I want to exclude those wher ...

Challenges posed by constant integer pointer

I have come across a unique approach to handling global arrays in someone else's code that I strongly believe is flawed. The original creator of the code swears by it, but I am looking to gather arguments against this method. Below is a simplified ver ...

Encountered unexpected character error while parsing JSON data

I am encountering the following error message: JSON.parse: unexpected character when I execute this code in firebug: JSON.parse({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":fals ...

Collapse in Bootstrap without any Animation

How can I add animation to the Bootstrap Collapse feature on my website? I am using an icon from the Font Awesome library to trigger the collapse effect, but currently, it just pops up without any animation. What could be causing this issue? You can view ...

What is preventing me from translating JS Canvas Image?

I've been struggling with using ctx.translate() to translate images on a canvas. No matter what I do, it just won't work. I've spent a good amount of time trying to troubleshoot the issue. Here's the snippet of code I'm working wit ...

Adjust the width of the graphics on both sides of the text based on the length of the text content

Is there a way to center an H1 tag between two graphics using CSS or jquery/javascript? The width of the H1 text will vary depending on the page. The dot on the left should remain at the edge of the site, and the line should extend to meet the edge of the ...