not getting Country code from intlTelInput input [duplicate] - javascript

I've installed the plugin and Its displaying the countries correctly and working fine, but when I submit the form that has the input of type = "tel", the form does not submit the country code, I don't know how this works, but I did read all of instructions in https://github.com/jackocnr/intl-tel-input page, but I didn't understand how to get the full number + code country together so I can insert them into MySQL data base.
I'm so beginner, and just confused how to get this to work fine.
Sorry if the question is not that hard, but I really don't know how this works.
The jQuery code I have:-
$("#telephone").intlTelInput({
initialCountry: "sd",
separateDialCode: true
});

intlTelInput option:
hiddenInput
Add a hidden input with the given name. Alternatively, if your input name contains square brackets (e.g. name="phone_number[main]") then it will give the hidden input the same name, replacing the contents of the brackets with the given name (e.g. if you init the plugin with hiddenInput: "full", then in this case the hidden input would have name="phone_number[full]"). On submit, it will automatically populate the hidden input with the full international number (using getNumber). This is a quick way for people using non-Ajax forms to get the full international number, even when nationalMode is enabled. Avoid this option when using Ajax forms and instead just call getNumber to get the full international number to send in the request. Note: requires the input to be inside a form element, as this feature works by listening for the submit event on the closest form element. Also note that since this uses getNumber internally, firstly it requires the utilsScript option, and secondly it expects a valid number and so should only be used after validation.
var phone_number = window.intlTelInput(document.querySelector("#phone_number"), {
separateDialCode: true,
preferredCountries:["in"],
hiddenInput: "full",
utilsScript: "//cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/js/utils.js"
});
$("form").submit(function() {
var full_number = phone_number.getNumber(intlTelInputUtils.numberFormat.E164);
$("input[name='phone_number[full]'").val(full_number);
alert(full_number)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/css/intlTelInput.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/js/intlTelInput.min.js"></script>
<body>
<form>
<input type="tel" name="phone_number[main]" id="phone_number" />
<button type="submit" name="save">Save</button>
</form>
</body>
Php Code
You can get full number like
$phone_number = $_REQUEST['phone_number']['full'];

<form method="post">
<input type="hidden" id="code" name ="code" value="1" >
<input type="text" id="phone" name ="phone" value="" >
<button type="submit" >Send Verification Text</button>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#phone").intlTelInput({
preferredCountries: ["us", "ca"],
separateDialCode: true,
initialCountry: ""
}).on('countrychange', function (e, countryData) {
$("#code").val(($("#phone").intlTelInput("getSelectedCountryData").dialCode));
});
});
</script>

Submit the form with this:
HTML:
<form action="post">
<div class="select">
<input type="hidden" id="phone2" name="phone"/>
<input type="tel" id="phone" name="phone-full">
</div>
</form>
JAVASCRIPT:
$("form").submit(function() {
$("#phone2").val($("#phone").intlTelInput("getNumber"));
});

Searching a bit in the link you posted I found a nice example doing what you're asking
Taking some inspiration from the example, here is the code
HTML
<form action="post">
<div class="select">
<input type="hidden" id="country" name="country"/>
<input type="tel" id="phone" name="phone">
</div>
</form>
JS
var input = $('#phone');
var country = $('#country');
var iti = intlTelInput(input.get(0))
// listen to the telephone input for changes
input.on('countrychange', function(e) {
// change the hidden input value to the selected country code
country.val(iti.getSelectedCountryData().iso2);
});

They have a function already. This will return something like this.
phoneInput.getSelectedCountryData();
{
name: "Afghanistan (‫افغانستان‬‎)",
iso2: "af",
dialCode: "93"
}

// Add code in intlTelInput.js to use current location show code
$currentCountry = 'us';
$.ajax({
url: 'http://ip-api.com/json/',
async: false,
success:function(data){
$currentCountry = data.countryCode.toLowerCase();
// console.log(data.countryCode.toLowerCase());
}
})
$selected = $('.country_code').attr('country_iso_code2') != undefined ? $('.country_code').attr('country_iso_code2') : $currentCountry;
// console.log($selected);
var pluginName = "intlTelInpu`enter code here`t", defaults = {
preferredCountries: [ $selected ],
// united states and united kingdom
initialDialCode: true,`enter code here`
americaMode: false,
onlyCountries: []
};

HTML
(ng2TelOutput)="getNumberCellNo1($event)"
Javascript
getNumberCellNo1(e:any)
{
this.cell_code1.setNumber(e)
this.cellnumber1=e
}
The getNumber() will give you the country code and number as +919843133490.
The setNumber will set the country flag and place the number inn input field.
Hope it helped. Any further queries can be asked.

HTML CODE
Use this html code
<input type="text" name="ccode" id="ccode">
<input type="tel" id="phone" name="phone" >
JAVA SCRIPT CODE
//Country code
var titilec=title.split(":");
document.getElementById('ccode').value=titilec[1];
Add the above js code in your intlTelInput.js file after the below code
// update the selected country's title attribute
var title = countryCode ? "".concat(this.selectedCountryData.name, ": +").concat(this.selectedCountryData.dialCode) : "Unknown";
this.selectedFlag.setAttribute("title", title);

For getting country short code and dial code add below lines(hidden inputs) inside the <form>,
<input type="hidden" name="dialCode" id="dialCode">
<input type="hidden" name="countryCode" id="countryCode">
Add below javascript code
$('.iti__country-list li').click(function(){
$("#dialCode").val($(this).data('dial-code'));
$("#countryCode").val($(this).data('country-code-code'));
})
Here, you are getting dial code and country short code string in the hidden inputs when the code is selected from the dropdown.
And after the form submitting, concatenate the dial code and mobile number to save in the database.

HTML
<input type="tel" name="phone" class="phone-inteltel" required>
Javascript
var input = document.querySelector(".phone-inteltel");
window.intlTelInput(input, {
separateDialCode: true,
initialCountry: "auto",
hiddenInput: "phone",
geoIpLookup: function (callback) {
$.get('https://ipinfo.io', function () { }, "jsonp").always(function (resp) {
var countryCode = (resp && resp.country) ? resp.country : "tr";
callback(countryCode);
});
},
utilsScript: "https://intl-tel-input.com/node_modules/intl-tel-input/build/js/utils.js?1638200991544" // just for formatting/placeholders etc
});

Related

How can i get the value of the country code Selected [duplicate]

I've installed the plugin and Its displaying the countries correctly and working fine, but when I submit the form that has the input of type = "tel", the form does not submit the country code, I don't know how this works, but I did read all of instructions in https://github.com/jackocnr/intl-tel-input page, but I didn't understand how to get the full number + code country together so I can insert them into MySQL data base.
I'm so beginner, and just confused how to get this to work fine.
Sorry if the question is not that hard, but I really don't know how this works.
The jQuery code I have:-
$("#telephone").intlTelInput({
initialCountry: "sd",
separateDialCode: true
});
intlTelInput option:
hiddenInput
Add a hidden input with the given name. Alternatively, if your input name contains square brackets (e.g. name="phone_number[main]") then it will give the hidden input the same name, replacing the contents of the brackets with the given name (e.g. if you init the plugin with hiddenInput: "full", then in this case the hidden input would have name="phone_number[full]"). On submit, it will automatically populate the hidden input with the full international number (using getNumber). This is a quick way for people using non-Ajax forms to get the full international number, even when nationalMode is enabled. Avoid this option when using Ajax forms and instead just call getNumber to get the full international number to send in the request. Note: requires the input to be inside a form element, as this feature works by listening for the submit event on the closest form element. Also note that since this uses getNumber internally, firstly it requires the utilsScript option, and secondly it expects a valid number and so should only be used after validation.
var phone_number = window.intlTelInput(document.querySelector("#phone_number"), {
separateDialCode: true,
preferredCountries:["in"],
hiddenInput: "full",
utilsScript: "//cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/js/utils.js"
});
$("form").submit(function() {
var full_number = phone_number.getNumber(intlTelInputUtils.numberFormat.E164);
$("input[name='phone_number[full]'").val(full_number);
alert(full_number)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/css/intlTelInput.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.3/js/intlTelInput.min.js"></script>
<body>
<form>
<input type="tel" name="phone_number[main]" id="phone_number" />
<button type="submit" name="save">Save</button>
</form>
</body>
Php Code
You can get full number like
$phone_number = $_REQUEST['phone_number']['full'];
<form method="post">
<input type="hidden" id="code" name ="code" value="1" >
<input type="text" id="phone" name ="phone" value="" >
<button type="submit" >Send Verification Text</button>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#phone").intlTelInput({
preferredCountries: ["us", "ca"],
separateDialCode: true,
initialCountry: ""
}).on('countrychange', function (e, countryData) {
$("#code").val(($("#phone").intlTelInput("getSelectedCountryData").dialCode));
});
});
</script>
Submit the form with this:
HTML:
<form action="post">
<div class="select">
<input type="hidden" id="phone2" name="phone"/>
<input type="tel" id="phone" name="phone-full">
</div>
</form>
JAVASCRIPT:
$("form").submit(function() {
$("#phone2").val($("#phone").intlTelInput("getNumber"));
});
Searching a bit in the link you posted I found a nice example doing what you're asking
Taking some inspiration from the example, here is the code
HTML
<form action="post">
<div class="select">
<input type="hidden" id="country" name="country"/>
<input type="tel" id="phone" name="phone">
</div>
</form>
JS
var input = $('#phone');
var country = $('#country');
var iti = intlTelInput(input.get(0))
// listen to the telephone input for changes
input.on('countrychange', function(e) {
// change the hidden input value to the selected country code
country.val(iti.getSelectedCountryData().iso2);
});
They have a function already. This will return something like this.
phoneInput.getSelectedCountryData();
{
name: "Afghanistan (‫افغانستان‬‎)",
iso2: "af",
dialCode: "93"
}
// Add code in intlTelInput.js to use current location show code
$currentCountry = 'us';
$.ajax({
url: 'http://ip-api.com/json/',
async: false,
success:function(data){
$currentCountry = data.countryCode.toLowerCase();
// console.log(data.countryCode.toLowerCase());
}
})
$selected = $('.country_code').attr('country_iso_code2') != undefined ? $('.country_code').attr('country_iso_code2') : $currentCountry;
// console.log($selected);
var pluginName = "intlTelInpu`enter code here`t", defaults = {
preferredCountries: [ $selected ],
// united states and united kingdom
initialDialCode: true,`enter code here`
americaMode: false,
onlyCountries: []
};
HTML
(ng2TelOutput)="getNumberCellNo1($event)"
Javascript
getNumberCellNo1(e:any)
{
this.cell_code1.setNumber(e)
this.cellnumber1=e
}
The getNumber() will give you the country code and number as +919843133490.
The setNumber will set the country flag and place the number inn input field.
Hope it helped. Any further queries can be asked.
HTML CODE
Use this html code
<input type="text" name="ccode" id="ccode">
<input type="tel" id="phone" name="phone" >
JAVA SCRIPT CODE
//Country code
var titilec=title.split(":");
document.getElementById('ccode').value=titilec[1];
Add the above js code in your intlTelInput.js file after the below code
// update the selected country's title attribute
var title = countryCode ? "".concat(this.selectedCountryData.name, ": +").concat(this.selectedCountryData.dialCode) : "Unknown";
this.selectedFlag.setAttribute("title", title);
For getting country short code and dial code add below lines(hidden inputs) inside the <form>,
<input type="hidden" name="dialCode" id="dialCode">
<input type="hidden" name="countryCode" id="countryCode">
Add below javascript code
$('.iti__country-list li').click(function(){
$("#dialCode").val($(this).data('dial-code'));
$("#countryCode").val($(this).data('country-code-code'));
})
Here, you are getting dial code and country short code string in the hidden inputs when the code is selected from the dropdown.
And after the form submitting, concatenate the dial code and mobile number to save in the database.
HTML
<input type="tel" name="phone" class="phone-inteltel" required>
Javascript
var input = document.querySelector(".phone-inteltel");
window.intlTelInput(input, {
separateDialCode: true,
initialCountry: "auto",
hiddenInput: "phone",
geoIpLookup: function (callback) {
$.get('https://ipinfo.io', function () { }, "jsonp").always(function (resp) {
var countryCode = (resp && resp.country) ? resp.country : "tr";
callback(countryCode);
});
},
utilsScript: "https://intl-tel-input.com/node_modules/intl-tel-input/build/js/utils.js?1638200991544" // just for formatting/placeholders etc
});

intl-tel-input send hidden input send value to Google sheets

I have an HTML form using intl-tel-input for automatic country detection based on the IP.
I am trying to send the values of the form, but I am getting in Google sheets only the phone number without prefix
<form>
<input type="text" name="first_name" placeholder="First Name">
<input name="phone" type="tel" id="phone" placeholder="phone Number">
<input type="hidden" id="country" name="country">
</form>
this is the JS code
var input = document.querySelector("#phone");
// window.intlTelInput(input, {
// // any initialisation options go here
// });
var iti = intlTelInput(input, {
initialCountry: "auto",
geoIpLookup: function(success, failure) {
$.get("https://ipinfo.io", function() {}, "jsonp").always(function(resp) {
var countryCode = (resp && resp.country) ? resp.country : "";
success(countryCode);
});
},
});
var country = $('#country');
var iti = intlTelInput(input.get(0))
// listen to the telephone input for changes
input.on('countrychange', function(e) {
// change the hidden input value to the selected country code
country.val(iti.getSelectedCountryData().iso2);
});
Does Google sheets accepts input from hidden fields?
There is any way that I can get the country code separated or at least the full number (country_code+phone_number)
Thank in advance.

Jquery not returning the values in form INPUTs

I have a login form on a modal jquery dialog with the usual 2 text INPUTs. When I enter a login name and password then click the submit, the call back function is called.
The first thing the callback does is try to extract the values of the two INPUTs, but the values returned are empty strings (I have a breakpont here, and have even stepped through the jquery processing of the objects - they objects are correctly identified as the fields on the form, but value="" for both).
At this point I can still see the values in the form, and when the callback exits and the focus goes back to the form, the values are still in the INPUTS. I also tried .prop("value") rather than .val(), but the result was the same.
I just can't figure why I can't read the values - any help appreciated.
<form id="cp-loginform" action="/cypo/index.php" method="POST" >
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50"></p>
<input type="submit" id="cp-submit" name = "submit" onclick="ProcessLogin()" ></p>
</form>
function ProcessLogin() {
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
}
PROBLEM RESOLVED:
I felt that this was a scope issue. The form itself was obviously OK (if submitted from the dialog it worked) - it was just the attempt to check the INPUT values using jquery that wasn't working.
I found that my select had to start with the dialog element and include a descendent path to my INPUTs. It's as if the dialog puts a wrapper around the elements inside so they are no longer visible as owned by the document.
If I login with xxx and zzz and step therough the following code I see this:
var loginval = $("#cploginname").val(); << = ""
var passwordval = $("#cppassword").val(); << = ""
var loginval = $("#cp-loginform #cploginname").val(); << = ""
var passwordval = $("#cp-loginform #cppassword").val(); << = ""
var loginval = $("#cpdialog #cp-loginform #cploginname").val(); << = "xxx"
var passwordval = $("#cpdialog #cp-loginform #cppassword").val(); << = "zzz"
console.log(loginval.concat(" ",passwordval));
I can't say I understand what's going on, but I have a solution so I am happy. Thanks to all who answered.
FINAL WORD
Thanks to #CMedina, I now understand. The form was defined in a hidden DIV at the top of my BODY section, and I passed $("#loginform") to a f() that created the dialog. The dialog was added to the DOM just before the . I had missed the fact that my original form was still in the DOM, so I was referencing that, not the dialog copy. When I included the dialog wrapper in the path, I finally 'found' the second copy.
Your button is the type submit (their natural behavior is to send the form). Remove the onclick in your button html.
<input type="submit" id="cp-submit" name = "submit">
You must add preventDefault to prevent submit the form and do what you want. Add the code JS for the button onclick event
$("#cp-submit").on("click", function(e){
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
});
Result: https://jsfiddle.net/cmedina/svjqb2a4/
Try it :
<html>
<head>
</head>
<body>
<form id="cp-loginform" action="/cypo/index.php" method="POST">
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50">
<input type="submit" id="cp-submit" name ="submit" onclick="ProcessLogin(event)">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function ProcessLogin(e) {
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
alert(loginval.concat(" ",passwordval));
}
</script>
</body>
</html>

Javascript onKeyUp condition doesnt work when speed typing

my simple html file code
Site Name: <input id="name" type="text" onkeyup="myFunction1(event,this)">
URL : <input id="url" type="text">
javascript code
function myFunction1(event,t){
var nameval= document.getElementById("name").value;
var urlval= document.getElementById("url").value;
var namelen = nameval.length;
var urllen = urlval.length;
var res = nameval.substring(1, namelen);
if(res.length == urllen){
document.getElementById("url").value = t.value;
}
else{
alert("string lengths are not matching");
}
}
what i want to do when user type Site Name in textbox, same text should reflect to URL textbox if name and url text boxes have same text lenghts . but when i speed type site name, my if condition fail after typing few characters and it goes to else block. i dont know why this happening. can anyone help me to improve this code?
Using the onkeyup event isn't your best option for what you are trying to do. You can use the oninput event instead. Here's the modified HTML:
Site Name: <input id="name" type="text" oninput="myFunction1(event,this)">
URL : <input id="url" type="text">

Prefill field value and readonly

I have a form with several fields and I need to customize some fields using javascript for allow me to:
prefill the value "New York" for the field "city"
make the field "email" readonly
prefill AND make readonly the field "country"
To get the result of point 1, I used this code which works well:
<script type="text/javascript">function on_form_loaded(event) {
if (event=='reserve')
document.getElementById('city').setAttribute("value", "New York");
}</script>
For get the result of point 2, I used this code which works well:
<script type="text/javascript">function on_form_loaded(event) {
if (event=='reserve')
document.getElementById('email').readOnly=true;
}</script>
But now I don't see how to "mix" prefill/readonly paramters for get the result of point 3.
Someone can help ?
In addition I would like shorten the code for avoid to include a single javascript for each field. I make some test but without success. if you can give me some example...
I'm not sure what you're missing but try this
var country = document.getElementById('country');
country.value = "USA";
country.readOnly = true;
As jimjimmy1985 mentioned in the comments above, you can also do this in markup
<input name="country" id="country" value="USA" readonly>
Assuming You're using 'on...="on_form_loaded"' as attribute in the form tag and having no problem to add jQuery, You may try:
<script type="text/javascript">
jQuery('#ID_OF_YOUR_FORM').ready( function(event) {
if (event=='reserve') {
var form_object = jQuery(this);
form_object.find('#city').value('New York').end()
.find('#country').value('USA').end()
.find('#country, #email').attr('readonly', true);
}
});
</script>
Where ID_OF_YOUR_FORM has to be replaced by Your forms individual ID.

Categories