Reputation: 3285
I am using intl-tel-input to get peoples phone code and country. When they select the flag and code I have some jQuery with gets the country and code separately and populates hidden fields...
Here is the entire object which handles these operations:
var telInput = {
init: function(){
this.setTelInput();
this.cacheDOM();
this.bindEvents();
},
cacheDOM: function(){
this.$countryCode = $('input[name=country_code]');
this.$countryName = $('input[name=country_name]');
this.$country = $('.country');
},
bindEvents: function(){
this.$country.on('click', this.getTelInput.bind(this));
},
setTelInput: function(){
$('input[name=phone]').intlTelInput({
preferredCountries: [
'gb'
],
});
},
getTelInput: function(e){
var el = $(e.target).closest('.country');
var countryCode = el.attr('data-dial-code');
var countryName = el.find('.country-name').text();
this.$countryCode.val(countryCode);
this.$countryName.val(countryName);
},
}
Problem
The problem is the click event in the bindEvents
method... the phone picker works but the onclick
event is not being triggered to populate my hidden fields.
Upvotes: 0
Views: 327
Reputation: 4219
You need to make sure that you cache the DOM after it has been rendered. Here's a simplified example.
var telInput = {
init: function(){
this.cacheDOM();
this.bindEvents();
},
cacheDOM: function() {
this.$country = $('.country');
},
bindEvents: function() {
this.$country.on('click', function() {
// console.log('Triggered');
});
}
}
$(document).ready(function() {
telInput.init();
});
Also, plugin's event countrychange
could be useful in your case.
$("#country-select-element").on("countrychange", function(e, countryData) {
// do something with countryData
});
I would also suggest you to have a look at the public methods. It has some useful methods that you could use to achieve the same result.
Upvotes: 1