简体   繁体   中英

how to return new input value

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>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM