How To Auto Select Country Using IP Lookup In jQuery

Websolutionstuff | May-15-2023 | Categories : Laravel PHP jQuery

In this article, we will see how to auto select a country using IP lookup in jquery. Here, we will learn about autoselect the user's country and validating the telephone number. International Telephone Input supports setting the initial selected country to the user's current country, using an IP lookup service. 

So, let's see intltelinput set country code dynamically, country code with flag dropdown jquery, international telephone input jquery validation, autoselect user's country and validate telephone number, international phone number validation javascript.

Here, we use the International Telephone Input plugin for auto select user country with validation. International Telephone Input is a plugin, written in pure JavaScript, for handling international telephone numbers.

You must enable two initialization options. First, you must set the initialCountry option to "auto". This tells the plugin to use the IP lookup service to determine the user's country. Second, you must set the geoIpLookup option to a function that will make the IP lookup request and return the country code.

Example:

<html lang="en">
<head>
	<title>How To Auto Select Country Using IP Lookup In jQuery - Websolutionstuff</title>
	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/build/css/intlTelInput.css">
</head>
<body>
	<div class="col-md-6 offset-md-2">
		<div class="container mt-5">
			<div class="card">
				<div class="card-header">
					<strong>How To Auto Select Country Using IP Lookup In jQuery - Techsolutionstuff</strong>
				</div>
				<div class="card-body">
					<h6 class="card-title">Phone Number:</h6>
					<input id="phone" type="tel">
					<span id="valid-msg" class="hide">✓ Valid</span>
					<span id="error-msg" class="hide"></span>
				</div>
			</div>
		</div>
	</div>
</body>
</html>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/js/intlTelInput.min.js"></script>

CSS:

.hide {
  display: none;
}
#valid-msg {
  color: #00c900;
}

jQuery:

It is important to validate any user input before saving it to your backend. With International Telephone Input, you can use the isValidNumber method, which returns true or false. If it returns false, and you'd like more detail, you can then use the getValidationError method to get more information.

const input = document.querySelector("#phone");
const errorMsg = document.querySelector("#error-msg");
const validMsg = document.querySelector("#valid-msg");

// here, the index maps to the error code returned from getValidationError - see readme
const errorMap = ["Invalid number", "Invalid country code", "Too short", "Too long", "Invalid number"];

// initialise plugin
const iti = window.intlTelInput(input, {
  initialCountry: "auto",
  geoIpLookup: callback => {
    fetch("https://ipapi.co/json")
      .then(res => res.json())
      .then(data => callback(data.country_code))
      .catch(() => callback("us"));
  },
  utilsScript: "https://cdn.jsdelivr.net/npm/[email protected]/build/js/utils.js"
});

const reset = () => {
  input.classList.remove("error");
  errorMsg.innerHTML = "";
  errorMsg.classList.add("hide");
  validMsg.classList.add("hide");
};

// on blur: validate
input.addEventListener('blur', () => {
  reset();
  if (input.value.trim()) {
    if (iti.isValidNumber()) {
      validMsg.classList.remove("hide");
    } else {
      input.classList.add("error");
      const errorCode = iti.getValidationError();
      errorMsg.innerHTML = errorMap[errorCode];
      errorMsg.classList.remove("hide");
    }
  }
});

// on keyup / change flag: reset
input.addEventListener('change', reset);
input.addEventListener('keyup', reset);

Output:

how_to_auto_select_country_using_ip_lookup_in_jquery_output

 


You might also like:

Recommended Post
Featured Post
How To Create Dynamic Pie Chart In Laravel 8
How To Create Dynamic Pie Char...

In this article, we will see how to create a dynamic pie chart in laravel 8. Pie charts are used to represent...

Read More

Oct-02-2020

How to Filter Datatable using Dropdown in Laravel 10
How to Filter Datatable using...

Hello developers! 👋 Ever found yourself dealing with a DataTable in Laravel and wished for a nifty way to filter th...

Read More

Feb-07-2024

How To Get Current Route In React JS
How To Get Current Route In Re...

As a web developer using React JS, I've come to appreciate the power and efficiency of this JavaScript library. Its...

Read More

Aug-11-2023

Laravel whereDate and whereDay Example
Laravel whereDate and whereDay...

In this article, we will see laravel whereDate and whereDay examples. As you all know laravel provides many in...

Read More

Jan-21-2021