I would like to know how to create a dropdown menu that shows the country name, flag, and code based on the

I have successfully generated the telephone input field.

One requirement is to display the Country flag along with the country name as soon as the dropdown is selected. Another requirement is that once the country is selected, it should display the country code in the next text field.

The output should look like this:

https://i.stack.imgur.com/dCv53.png

$("#mobile-number").intlTelInput({
  initialCountry: "auto",
  geoIpLookup: function(callback) {
    $.get('https://ipinfo.io', function() {}, "jsonp").always(function(resp) {
      var countryCode = (resp && resp.country) ? resp.country : "";
      callback(countryCode);
    });
  },
  utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/11.0.9/js/utils.js" // just for formatting/placeholders etc
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js></script>
<script src="https://www.jquery-az.com/jquery/js/intlTelInput/intlTelInput.js"></script>
<link href="https://www.jquery-az.com/jquery/css/intlTelInput/demo.css" rel="stylesheet" />
<link href="https://www.jquery-az.com/jquery/css/intlTelInput/intlTelInput.css" rel="stylesheet" />

<h1>A demo with IP lookup</h1>
<form style="margin-left:150px;">
  <input type="tel" id="mobile-number" placeholder="e.g. +1 702 123 4567">
</form>

Answer №1

I attempted to implement this functionality using jQuery.

$("#mobile-number").intlTelInput({
  initialCountry: "auto",
  geoIpLookup: function(callback) {
    $.get('https://ipinfo.io', function() {}, "jsonp").always(function(resp) {
      var countryCode = (resp && resp.country) ? resp.country : "";
      callback(countryCode);
      init();
    });
  },
  utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/11.0.9/js/utils.js" // just for formatting/placeholders etc
});
function init() {
    $(".selected-flag").css("width", "150px");
    $(".selected-flag").append($("<div id='country-name'>"+name+"</div>").css({
        "position": "absolute",
        "top": "0",
        "bottom": "0",
        "right": "0",
        "width": "100",
        "display": "flex",
        "align-items": "center",
        "overflow": "hidden",
        "white-space": "nowrap"
    }));
    $("#mobile-number").css({"padding-left":"150px", "width":"300px"});
    showCountryAndCode();
};
$(".country-list li").click(function() {
    showCountryAndCode();
});
function showCountryAndCode() {
    setTimeout(() => {
        let name = $("li.active span.country-name").text();
        name = name.indexOf('(') > 0 ? name.substr(0, name.indexOf('(') - 1) : name;
        const code = $("li.active span.dial-code").text();
        $("#country-name").text(name);
        $("#mobile-number").val(code+" ");
    }, 0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://www.jquery-az.com/jquery/js/intlTelInput/intlTelInput.js"></script>
<link href="https://www.jquery-az.com/jquery/css/intlTelInput/demo.css" rel="stylesheet" />
<link href="https://www.jquery-az.com/jquery/css/intlTelInput/intlTelInput.css" rel="stylesheet" />

<h1>A demo with IP lookup</h1>
<form style="margin-left:150px;">
  <input type="tel" id="mobile-number" placeholder="e.g. +1 702 123 4567">
</form>

I hope that these instructions prove useful to you.

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

Images that have been resized on Android appear blurry when viewed on the second page

Customizing the Toolbar: #main_bar { background: url(../images/logo.jpg) 99% 50% no-repeat; background-size: auto 80%; } The original size of logo.jpg is 220x266px The toolbar has a fixed height of 46px Therefore, the background image appears t ...

What is the best way to interact with the member variables and methods within the VideoJs function in an Angular 2 project

Having an issue with accessing values and methods in the videojs plugin within my Angular project. When the component initializes, the values are showing as undefined. I've tried calling the videojs method in ngAfterViewInit as well, but still not get ...

Unable to trigger AJAX POST with jQuery click handler

Important Note: Personally, I have a preference for utilizing jQuery over the shorthand $; although it involves more typing, I find it to be more readable. I am working on a simple form that allows users to input their first and last names as well as an e ...

My Ajax script is not recognizing the select tag value?

I am struggling with an ajax script that is supposed to send data from a contact form to a PHP script. The main issue I'm facing is that I can't seem to retrieve the value from the "select" tag. My knowledge of JavaScript/ajax is limited, so plea ...

What is the best way to calculate the difference between two dates in MongoDB?

I have two key dates: the sales_date (date of service sale) and the cancellation_date (date of service cancellation). I am looking to calculate tenure by month by subtracting the cancellation_date from the sales_date. Currently, this is the code I have: ...

Creating dynamic styles with Material-UI's useStyles

Attempting to implement the same logic using material-ui's useStyle feature <div className={'container ' + (state.unlocked ? 'containerUnlocked' : '')}> I thought it might look like this: <div className={`${clas ...

I am currently working on creating a timer and I am looking to position these three buttons in a circular formation

I want to create a stopwatch with 3 responsive buttons arranged in a circular layout. I have successfully built a responsive circle and now need help adding the buttons inside the circle next to the timer. To view the code, click here: https://jsfiddle.ne ...

The file size exceeds the server's upload limit, despite making changes to the php.ini file

I've encountered a problem trying to upload an .OBJ file to the server, resulting in an 'Error 1' message. The uploaded file surpasses the upload_max_filesize directive specified in php.ini This error is detailed on this page - http://ph ...

Turn off scroll bar to create a seamless browsing experience on your website

As I work on creating the frontend for a single-page website with seamless scrolling between divs, I'm looking to eliminate mouse scrolling altogether. I understand that using overflow:hidden; can hide scroll bars, but my goal is to make the page scr ...

Browsing through a collection of JSON objects with a user interface

I need a way to filter and display a list of Dogs based on a search query. I initially stored the data in an array within the state, but with an increasing number of entries, I've decided to switch to JSON format for better management. However, I&apo ...

Angular list with a repeating group of radio buttons

I have a set of 'options', which consists of the following: {Id: 1, Label: "option 1"}, {Id: 2, Label: "option 2"} Additionally, I have a list of 'products' structured as follows: {Id: 1, Name: "Name 1", Recommend: options[0]}, {Id: ...

Controlling the angular bootstrap modal form with ease

I am having trouble accessing the form in the modal controller (Plunkr). The variable myForm doesn't seem to be accessible. How can I make the alert call work correctly: angular.module('plunker', ['ui.bootstrap']); var ModalDemoCt ...

What is the best way to retrieve the color of a WebElement when dealing with a complex CSS structure in Webdriver

I am currently trying to determine if the color of a specific page changes immediately after clicking on a button designed to alter the color of an element within that page. My goal is to extract the RGB value stated as rgb(183,168,168); in this particul ...

Resource loading unsuccessful: server encountered a status of 500 (Internal Server Error)

I'm struggling to figure out why I keep getting an Internal Server Error when trying to call a web service in my HTML page using JavaScript and Ajax. Here is the error message: Failed to load resource: the server responded with a status of 500 (Int ...

Placing a table within a div causes the div to expand in width beyond 100%

A situation has arisen where a table with a large number of columns (30 columns) is being affected by the white-space:nowrap style set on each th tag, causing the parent div to stretch unnaturally. How can this issue be resolved and allow for a horizonta ...

The issue with the Hidden Content feature in the Slick Carousel is that it does not function correctly on the

There are some related topics worth exploring, such as: Slick carousel center class not working when going from last item to first item Despite trying various solutions, the issue still persists in my code. My goal is to have each item displayed in the ce ...

Guide on implementing CSS modules in a WordPress plugin built with React

Within one of my tsx files, I included this line: import styles from "../../styles/buyTicket.module.css"; This resulted in the following error message: ERROR in /Applications/MAMP/htdocs/wp-content/plugins/tikex/tikexModule/components/BuyTicket/ ...

Avoid rendering the React component until the AJAX call has completed

Suppose the following code is given: componentDidMount() { $.ajax({ type: 'GET', url: '/data/', dataType: 'text', success: function(response) { this.setState({data: response}) ...

Background color vanishes (occasionally) on the contact section of my website when viewed in Chrome

My contact page has an issue that only occurs in Chrome, where the background disappears most of the time. This problem is not present in Firefox, Edge, or Safari on my TA's MacBook, but interestingly, hovering over a box resolves the issue on her dev ...

Obtaining a subset of data from firebase

I am currently working on retrieving a sub-collection from the Firestore database using Angular. In my database, I have a collection called 'Company' which contains fields for 'Name' and 'Id', as well as a sub-collection named ...