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 Login With Magic Link In Laravel 9
How To Login With Magic Link I...

In this article, we will see how to login with magic link in laravel 9. Here, we will learn passwordless login with...

Read More

Feb-01-2023

How to Update User Profile in Laravel 11
How to Update User Profile in...

Hello, laravel developers! In this article, we'll see how to update user profiles in laravel 11. Here, we'll cha...

Read More

Jul-12-2024

Laravel 10 Multiple Image Upload Example
Laravel 10 Multiple Image Uplo...

In this article, we will see laravel 10 multiple image examples. Here, we will learn about how to upload multiple i...

Read More

Mar-17-2023

How To Get Data Between Two Dates In Laravel 9
How To Get Data Between Two Da...

In this article, we will see how to get data between two dates in laravel 9. Here we will learn how to count d...

Read More

Dec-19-2022