Auto-formatting telephone input type
SolvedPJ47 Posted messages 77 Registration date Status Member Last intervention -
Hello,
I am looking to "auto format" my input so that it automatically gets the format XXXXXXXXXX regardless of what the user types.
I don't know if this should be done with a pre-existing function or some other programming.
Thank you in advance
J
3 answers
-
So I found some code but I'm trying to adapt it to my case
<form> <label for="#phone-input">Numéro de téléphone<span class="required">*</span></label> <input id="phone-input" type="tel" value="" name="PhoneIn" aria-label="Veuillez saisir votre numéro de téléphone" placeholder="ex. 1(111)-111-1111"> <p>Veuillez remplir les informations ci-dessus.</p> </form>
function phoneMask() { var num = $(this).val().replace(/\D/g,''); $(this).val(num.substring(0,1) + '(' + num.substring(1,4) + ')' + num.substring(4,7) + '-' + num.substring(7,11)); } $('[type="tel"]').keyup(phoneMask);But what links the HTML code to the JavaScript code?
Thank you
-
-
Hello @jordane45 StatusModerator
this is exactly what I did but:
I have the script line showing at the top of the page
head:
<script> function phoneMask() { var num = $(this).val().replace(/\D/g,''); $(this).val(num.substring(0,10)); } $('[type="tel"]').keyup(phoneMask); </script>html:
<div class="row mb-3"> <input name="tel" type="tel" placeholder="0000000000" /> </div>
and it doesn't work :-(
https://www.sapa-traitement.com/formulaire.php
J
-
-
This script requires jQuery ($), try it like this:
<script> document.addEventListener('DOMContentLoaded', () => { const inputs = document.querySelectorAll('[type="tel"]'); for (const input of inputs) { input.addEventListener('input', () => { input.value = phoneMask(input.value); }); } function phoneMask(value) { return value.replace(/\D/g, '').substring(0, 10); } }); </script> -
-
-
Hello,
Your request is vague.
auto format: what does that mean?
my input: which input?
In what context?
-
Hello @Phil_1857 StatusMember,
I am in an HTML contact form.
The input in question is the phone number.
I want the phone number to be formatted as 0102030405 even if the user adds dots or spaces.
Thank you