javascript - Get input value for country code with jquery [auto country by IP/intl-tel-input jquery library]
问题描述
I need to submit COUNTRY CODE to URL based on the selected country value.
Im using Intl-Tel-Input for this: https://github.com/jackocnr/intl-tel-input
Here is HTML code:
<form id="redirform" method="GET" action="#link">
<div class="gtd-form-wrapper">
<input type="hidden" id="country" name="country">
<div class="form-group">
<input name="phone" pattern="[0-9]*" id="phone" class="f w-input" data-value-missing="Use numbers only. No country code! No whitespaces!" required="required" placeholder="Phone">
</div>
<div class="form-group">
<button class="submit-button w-button gtd-form-submit" type="submit">SUBMIT</button>
</div>
</form>
Here is jQuery:
var input = document.querySelector("#phone");
window.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);
});
},
});
input.addEventListener('countrychange', function () {
$('#country').val(iti.getSelectedCountryData().iso2);
});
$('#redirform').on('submit',function(){
var $input = $(this).find("input[name=country]");
$('#country').val(iti.getSelectedCountryData().iso2);
});
Here is picture of what I have and what I need: PICTURE CLICK TO OPEN
解决方案
Seems you need to get the selected country value from the intl input. You don't need to add country input in HTML.
var intl = window.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);
});
},
});
$('#redirform').on('submit', function(e) {
e.preventDefault();
var countryData = iti.getSelectedCountryData();
var form = $('#form');
form.append($("<input>").attr("type", "hidden").attr("name", "country").val(countryData.iso2));
form.submit();
});
while the form is submitting, there is a hidden input is created and the value is set, so you don't need to worry about it.
Because you have told you to need to get the country value into URL, the form will submit as GET because the method of the form is GET.
Hope this will help you. thanks.
推荐阅读
- sql - Oracle SQL——从多行中选择特定数据到一行
- powershell - Invoke-Command 不会杀死远程机器上的进程
- kubernetes - helm生成的秘密不断被重新创建
- python - 使用python遍历嵌套列表以获取特定值
- c# - DataGrid 样式不允许打开 ContextMenu
- reactjs - 在重新渲染时更新依赖于另一个状态变量的其他状态变量的更好方法是什么?
- weekday - 如何在 Automation Anywhere 中获取/输出当前一周的所有天数?
- java - java 8项目可以依赖gradle中的java 11依赖吗
- laravel - 如何从 Laravel Voyager 中的数据透视表中删除相关数据
- javascript - 我怎样才能让这个图表在本地呈现?(D3.js)