Auto-formatting telephone input type
Solved
PJ47
Posted messages
77
Registration date
Status
Membre
Last intervention
-
PJ47 Posted messages 77 Registration date Status Membre Last intervention -
PJ47 Posted messages 77 Registration date Status Membre 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 réponses
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,
Your request is vague.
auto format: what does that mean?
my input: which input?
In what context?
Hello @Phil_1857 StatutMembre,
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
Hello,
You can place your script in your HTML file (by placing it between <script></script> tags before the </body> of your page.
Then remember to clear your browser cache before testing..
Hello @jordane45 StatutModérateur
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:
and it doesn't work :-(
https://www.sapa-traitement.com/formulaire.php
J
So.... no..... you didn't do what I told you to do...
Read carefully and apply...
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 @jless
thank you very much, it works perfectly!
I