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
Laravel 9 Many To Many Relationship Example
Laravel 9 Many To Many Relatio...

In this article, we will see laravel 9 many to many relationship example. Also, you can use many to many relationsh...

Read More

Apr-03-2022

How to Use Laravel Factory in Seeder
How to Use Laravel Factory in...

Laravel is a popular PHP framework known for its elegance and simplicity in building web applications. When it comes to...

Read More

Sep-13-2023

Laravel 9 CRUD Operation Example
Laravel 9 CRUD Operation Examp...

As we know Laravel 9 was officially released yesterday with many new functionalities like Symfony 6.0 components, Symfon...

Read More

Feb-10-2022

How To Convert Laravel Query To SQL Query
How To Convert Laravel Query T...

In this article, we will see how to convert a laravel query to an SQL query. Many times we required laravel query builde...

Read More

Oct-27-2022