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

Unable to modify the CSS properties of the titlebar in jQuery UI dialog

Is there a way to modify the background color of a jQuery UI dialog titlebar? Here is the code I am using: jQuery("#divId").dialog({ title: 'Information' }); jQuery("#divId .ui-dialog-titlebar").css("background-color", "red"); For m ...

Reset the text input field when the dropdown menu is set to 'no/other'

CURRENT: Choosing from a dropdown menu with options 'Yes' or 'No'. If 'Yes' is chosen: Display additional dropdowns/inputs for entry If 'No' is chosen: Conceal additional dropdowns/inputs WANT: I am looking to imp ...

What causes the discrepancy in margin values between desktop and mobile devices?

In my project, I have a collection of div elements that need to be spaced vertically from one another by the height of the window plus an additional 100px. However, I encountered a discrepancy when setting this margin using jQuery between mobile and deskto ...

Steps to isolate the "changed" values from two JSON objects

Here is a unique question that involves comparing JSON structures and extracting the differences. A JqTree has been created, where when the user changes its tree structure, both the "old" JSON and "new" JSON structures need to be compared. Only the values ...

Separating a variable within a Twitch bot: techniques and tips

I am working on setting up a feature in my Twitch bot where it can respond to the command !test [var]. For example, if someone types !test @jeff, the bot would reply with hello @jeff. Currently, I am using tmi. client.on('chat', function(channe ...

What techniques can I use to modify an object while it's being iterated through?

I've been attempting to manipulate the object while looping through it, but unfortunately, it's not working. How can I modify it so that the constant patient includes the property lastActivity inside the this.model array? My code looks like this ...

Struggling to concatenate array dynamically in Vue using ajax request

I am working on a Vue instance that fetches objects from a REST endpoint and showcases them on a web page. Most parts of the functionality work smoothly like filtering, however, there is an issue when attempting to add new objects by requesting a new "page ...

Is there a way to trigger the interval on the second load and subsequent loads, rather than the initial load?

I have implemented the use of setInterval in my recaptcha javascript code to address the issue of forms being very long, causing the token to expire and forcing users to refill the form entirely. While I am satisfied with how the current code functions, t ...

When the @change event is triggered, Vue data objects do not exhibit reactivity

Trying to figure out why the msg and show data parameters are not updating when triggered by @change. To ensure that these parameters are only updated upon successful file upload, I placed them inside the lambda function of onload: reader.onload = functio ...

What is the reason behind the improved performance I experience in Chrome with the Developer Console open?

Currently, I am developing a small canvas game completely from scratch using pure JavaScript. This game utilizes a 2D lighting algorithm that is akin to the one found here. It features only one light source and 25 polygons, resulting in approximately 30,0 ...

Tips for creating various instances of a single type within mock data

In my Schema.js, I have a simple schema and server setup: const typeDefs = gql` type Query { people: [Person!]! } type Person { name: String! age: Int! job: String } `; And here is my server configuration: const mocks = { Person ...

Retrieving date from timestamp in a node.js environment

Can someone help me figure out how to display my timestamp as the date in the front end? I've tried multiple methods without success. Here is the code snippet: formulaire.addEventListener('submit', posteValidation); /** * Function to add a ...

JavaScript and PHP open-source libraries for enabling voice chat functionality

Seeking assistance on incorporating voice-chat functionality into my website through PHP and JavaScript. Are there any open-source libraries available for this purpose? I am willing to utilize Flash if necessary, but limited to using only Flash, JavaScri ...

Unable to Render Data URI onto HTML5 Canvas

I have been attempting for quite some time and feeling frustrated. I am facing issues with my Data URI image not being able to write to my canvas for reasons unknown .... Here's the code snippet ... function addImage() { var allfiles = $("#postAtta ...

Modify the contents of a textbox by editing the text as you type

Text within the text box follows this format: login -u username -p password When entering this text, I want to substitute 'password' with a series of '*'s equal in length. For example: 'login -u <a href="/cdn-cgi/l/email-prot ...

Can you explain the concept of a "cURL" and guide me on how to use it effectively?

I'm currently working on setting up a Lyrebird application, but I only have a basic understanding of javascript and php. Despite my efforts to implement a cURL request from , I've encountered issues trying to get it to work in both javascript and ...

Leverage jQuery deferred objects to handle a dynamic amount of AJAX requests

When faced with multiple ajax requests, how can I execute them using deferreds? This is my approach: //qty_of_gets = 3; function getHTML(productID, qty_of_gets){ var dfd = $.Deferred(), i = 0, c = 0; // hypothetical cod ...

Issue with Material-UI Autocomplete: OnChange function causing interference with other functionalities

Handling the Autocomplete component has been a challenge for me, this is my current code snippet: <Autocomplete multiple id="checkboxes-tags-demo" options={ownerOptions2} disableCloseOnSelect filterSelectedOptio ...

Sorting price and date with Vue in Laravel - A beginner's guide

Attempting to sort by price and by date. See the code below. I decided not to use the controller for this sorting. Is it feasible to implement it here? It's somewhat functional, but there are some issues. When selecting price, it doesn't seem to ...

What is the best approach to simultaneously update an array using multiple threads in a Node.js environment?

Hey there, I'm trying to figure out how to make changes to the same array using 2 worker threads in Node.js. Can anyone help me with this? My issue is that when I add a value in worker thread 1 and then try to access it in worker thread 2, the second ...