I just can not understand what's the matter. There are 2 text fields in the template.

<input type="text" id="first"> <input type="text" id="second"> 

They are designed for phones. You need to make a mask and the ability to select a code. To do this, use jQuery and 2 plugins to it:

Wrote the initialization code for these two fields.

 function initPhoneMask(fieldId) { // ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·ΠΈΡ€ΡƒΠ΅ΠΌ ΠΏΠΎΠ»Π΅ для Ρ‚Π΅Π»Π΅Ρ„ΠΎΠ½Π° // https://github.com/jackocnr/intl-tel-input $(fieldId).intlTelInput({ autoHideDialCode: false, nationalMode: false, preferredCountries: ['ru'], utilsScript: "utils.js" }); // ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊ ΠΏΡ€ΠΈ ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΠΈ Ρ‚Π΅Π»Π΅Ρ„ΠΎΠ½Π½ΠΎΠ³ΠΎ ΠΊΠΎΠ΄Π° $(fieldId).on("countrychange", function(e, countryData) { if (countryData.iso2 === "ru") { $(this).mask('+7 (000) 000-00-00'); } else { $(this).unmask(); } }); // ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·ΠΈΡ€ΡƒΠ΅ΠΌ маску для Ρ‚Π΅Π»Π΅Ρ„ΠΎΠ½Π° // https://github.com/igorescobar/jQuery-Mask-Plugin $(fieldId).mask('+7 (000) 000-00-00'); } $(document).ready(function() { initPhoneMask("#first"); initPhoneMask("#second"); }); 

That is, the string

 $(fieldId).mask('+7 (000) 000-00-00'); 

initializes the field with the initially desired mask, and the handler hangs / unmasks the mask if the code of the desired country is selected / not selected.

BUT. When changing the country code, to any other mask does not disappear. If you remove the initialization code, then everything works, but at first the field is not initialized by the mask.

Why is that? MB someone came across?

  • That is, initialization overrides the changes in the handler? - Artur Kontvitskiy
  • I get an error - TypeError: e.target.unmask is not a function I print in console 'e' - exactly the element that is needed. - Artur Kontvitskiy
  • The same mistake. TypeError: e.currentTarget.unmask is not a function - Artur Kontvitskiy
  • Brought now. There is the object of the input that is needed. There are no problems with this. - Artur Kontvitskiy
  • So the problem is not in context. Another moment, are you sure that the methods work once, at the moment of initialization, and once at the moment of choosing the option? - test123

1 answer 1

In general, I solved the problem by manually calling the change event. Initialization removed.

 function initPhoneMask(fieldId) { // ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·ΠΈΡ€ΡƒΠ΅ΠΌ ΠΏΠΎΠ»Π΅ для Ρ‚Π΅Π»Π΅Ρ„ΠΎΠ½Π° // https://github.com/jackocnr/intl-tel-input $(fieldId).intlTelInput({ autoHideDialCode: false, nationalMode: false, preferredCountries: ['ru'], utilsScript: "utils.js" }); // ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚Ρ‡ΠΈΠΊ ΠΏΡ€ΠΈ ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΠΈ Ρ‚Π΅Π»Π΅Ρ„ΠΎΠ½Π½ΠΎΠ³ΠΎ ΠΊΠΎΠ΄Π° $(fieldId).on("countrychange", function(e, countryData) { if (countryData.iso2 === "ru") { $(this).mask('+7 (000) 000-00-00'); } else { $(this).unmask(); } $(fieldId).val(''); $(fieldId).val('+' + countryData.dialCode); }); var countryData = $(fieldId).intlTelInput('getSelectedCountryData'); $(fieldId).trigger('countrychange', [countryData]); }