I am using an intl-tel-input plugin to get the country code dropdown along with the country flag. I have another input field that has a country name as a dropdown. what I want is when the user selects any country from the country dropdown, then country code automatically gets selected in the country code dropdown. I used several methods but nothing works for me, I didn't find suitable documentation of this plugin too. this is my code.
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/16.0.8/css/intlTelInput.css" />
</head>
<body>
<div >
<div >
<h1>Select Country</h1>
</div>
<div >
<div >
<div >
<select name="country" id="country">
<option data-countryCode="DZ" value="213">Algeria</option>
<option data-countryCode="AD" value="376">Andorra</option>
<option data-countryCode="AO" value="244">Angola</option>
<option data-countryCode="AI" value="1264">Anguilla</option>
<option data-countryCode="AG" value="1268">Antigua & Barbuda
</option>
</select>
</div>
</div>
<div >
<input type="tel" id="txtPhone" />
</div>
</div>
</div>
<!-- Use as a jQuery plugin -->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/16.0.8/js/intlTelInput-jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#country").change(function()
{
let value=" " $(this).val();
$('#txtPhone').val(value);
})
var code = " 977"; // Assigning value from model.
$('#txtPhone').val(code);
$('#txtPhone').intlTelInput({
});
});
</script>
</body>
</html>
CodePudding user response:
To do what you require, call the setCountry
option of intlTelInput
and provide the country-code
data attribute value from the selected option
:
$(function() {
$("#country").change(function() {
let countryCode = $(this).find('option:selected').data('country-code');
let value = " " $(this).val();
$('#txtPhone').val(value).intlTelInput("setCountry", countryCode);
});
var code = " 977";
$('#txtPhone').val(code).intlTelInput();
});
<div >
<div >
<h1>Select Country</h1>
</div>
<div >
<div >
<div >
<select name="country" id="country">
<option data-country-code="DZ" value="213">Algeria</option>
<option data-country-code="AD" value="376">Andorra</option>
<option data-country-code="AO" value="244">Angola</option>
<option data-country-code="AI" value="1264">Anguilla</option>
<option data-country-code="AG" value="1268">Antigua & Barbuda
</option>
</select>
</div>
</div>
<div >
<input type="tel" id="txtPhone" />
</div>
</div>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/16.0.8/js/intlTelInput-jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/16.0.8/css/intlTelInput.css" />