Can I assign a country phone code based on country selection?

  • 5 August 2015
  • 2 replies
  • 74 views

See an example here.

When you seect a country, the form autopopulates the country phone code. For example, you select Argentina and it shows “+54” automatically.


2 replies

the sample URL is not working, can you please update it again.

I got this code that might help you (just edit the first 2 lines with the id of your country and phone field). The script also doesn’t let the user type any character except “+” and “0-9”, it also changes “00” to “+” when it’s typed at the beginning and it doesn’t accept spaces:

<script>
  var pais = document.getElementById("pais");
  var telefono = document.getElementById("telefono");
  
  function sustituyeTelefono() {
	if (telefono.value === '00') {
		telefono.value = '+'
	}
};

telefono.addEventListener('input', sustituyeTelefono);
  
function cambiaExtension() {  
  switch (pais.value) {
    case "Colombia":
      telefono.value = '+57';
      break;
    case "Mexico":
      telefono.value = '+52';
      break;
    case "Argentina":
      telefono.value = '+54';
      break;   	
    case "Chile":
      telefono.value = '+56';
      break;
    case "Peru":
      telefono.value = '+51';
      break;
    case "El Salvador":
      telefono.value = '+503';
      break;
    case "Honduras":
      telefono.value = '+504';
      break;
    case "Guatemala":
      telefono.value = '+502';
      break;
    default:
      telefono.value = '+';	

  }
};
  
pais.addEventListener('change', cambiaExtension);
  
function todoNumeros(){
      var invalidMatcher = /[^0-9+]+/;
      telefono.value = telefono.value.replace(invalidMatcher, '');
};
  
telefono.addEventListener('input', todoNumeros);

  
</script>

Reply