Me gustaría reemplazar mi antiguo valor de entrada (ancien_tel) por (nouveau_tel) para reformatear mi número de teléfono en el desenfoque. Me falta algo para devolver el valor a mi cuadro de texto de entrada.
<!DOCTYPE html> <html> <head> <title>Page Title</title> <meta charset="UTF-8"> <script> function reformatter() { var ancien_tel = document.querySelector("#telephone").value; var nouveau_tel = "(" + ancien_tel.substring(0, 3) + ") " + ancien_tel.substring(3, 6) + "-" + ancien_tel.substring(6).value; ancien_tel = nouveau_tel; } </script> </head> <body> Telephone:<br> <input type="text" id="telephone" onblur="reformatter()" maxlength="10"> </body> </html>en lugar de hacer
ancien_tel = nouveau_tel, hacer:
document.querySelector('#telephone').value = nouveau_tel El valor de ancien_tel se copia del valor del elemento #telephone , no se refiere a lo que hay dentro del elemento #telephone . Un código un poco menos detallado podría ser algo como:
function reformatter() { const telephone = document.querySelector("#telephone"); const ancien_tel = telephone.value; const nouveau_tel = "(" + ancien_tel.substring(0, 3) + ") " + ancien_tel.substring(3, 6) + "-" + ancien_tel.substring(6).value; telephone.value = nouveau_tel; }Todo lo que necesita para cambiar la función de reformateador
function reformatter() { var ancien_tel = document.querySelector("#telephone").value; var nouveau_tel = "(" + ancien_tel.substring(0, 3) + ") " + ancien_tel.substring(3, 6) + "-" + ancien_tel.substring(6); document.querySelector("#telephone").value = nouveau_tel; }