Use intl-tel-input with multiple instances of input fields

145 Views Asked by At

I am using intl-tel-input (https://github.com/jackocnr/intl-tel-input) to help users enter valid county codes in an application. All goes well when it comes to initializing and extracting data from instances with unique ID's. I need a little help when it comes to extracting data from multiple instances that use the same class. My example here CodePen Example successfully initialises multiple instances fine however I can quite get the syntax correct when it comes to using getNumber() from any or all of the multiple instances.

var input = document.querySelector("#phone");
var justPhone = window.intlTelInput(input, {
  separateDialCode: true,
  autoPlaceholder: false,
  utilsScript:
    "https://cdn.jsdelivr.net/npm/[email protected]/build/js/utils.js"
});

function getValue() {
  var number = justPhone.getNumber();
  alert(number);
}

// multiple variables

let ary = Array.prototype.slice.call(document.querySelectorAll(".phone"));
ary.forEach(function (el) {
  PhoneDisplay(el);
});
function PhoneDisplay(ary) {
  var iti = window.intlTelInput(ary, {
    separateDialCode: true,
    autoPlaceholder: false,
    utilsScript:
      "https://cdn.jsdelivr.net/npm/[email protected]/build/js/utils.js"
  });
}

function getValues() {
  var x = iti.getNumber();
  alert(x);
  //alert("how do I get these values?");
  // ??
}

I made progress using let ary = Array.prototype.slice.call(document.querySelectorAll(".phone")); and wraiing a function around the initiation. Failed after that.

1

There are 1 best solutions below

0
mplungjan On

Like this - you can use the getInstance method

Note the Array.from which is more elegant

https://codepen.io/mplungjan/pen/mdoGeGe

const inputs = document.querySelectorAll("[type=tel]");
inputs.forEach(input => {
  window.intlTelInput(input, {
    separateDialCode: true,
    autoPlaceholder: false,
    utilsScript: "https://cdn.jsdelivr.net/npm/[email protected]/build/js/utils.js"
  });
});

const getValues = () => {
  const values = Array.from(inputs)
  .map(input => window.intlTelInputGlobals.getInstance(input).getNumber());
  console.log(values);
};
document.getElementById('getValues').addEventListener('click', getValues);
body {
  margin: 20px;
}

input {
  width: 250px;
  padding: 10px;
  border-radius: 2px;
  border: 1px solid #ccc;
}

input::placeholder {
  color: #BBB;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/build/css/intlTelInput.css" />
<input type="tel" id="phone">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/js/intlTelInput.js"></script>
<hr>
<h1>Multiple instances with same class</h1>
<input type="tel" class="phone">
<input type="tel" class="phone">
<input type="tel" class="phone">
<input type="tel" class="phone">
<button type="button" id="getValues">GetTheseValues</button>