Home > Back-end >  how to return new input value
how to return new input value

Time:06-17

i would like to replace my old input value (ancien_tel) by (nouveau_tel) to reformat my phone number on blur i missing something to return the value into my input text box.

<!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>

CodePudding user response:

Instead of doing

ancien_tel = nouveau_tel

, do:

document.querySelector('#telephone').value = nouveau_tel

ancien_tel's value is copied from the #telephone element's value, it does not refer to what's inside the #telephone element. A bit less verbose code could be something like:

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;
}

CodePudding user response:

All you need to change the reformatter function

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;
}
  • Related