Add a space to the mobile phone number input box

Mobile phone number input box, set to 6005 1078 to automatically add spaces
question: [when you need to modify the number (6005), the cursor will jump to the end of the number immediately after deleting the number]
demand: [after deleting the number, the cursor will not jump to the end and can be modified normally]
ask colleagues, teachers, God to help me, this bug has been hanging with me for a long time. Thank you!

The

code is as follows
return function (input, space) {

  if (!input) {
    return ""
  }
  space = space || " "
  input = input.replace(/\s+/g, "") // 
  var valArry = input.split("")
  if (valArry.length > 7) {
    valArry = valArry.splice(7, 0, space)
  }
  if (valArry.length > 3) {
    valArry = valArry.splice(3, 0, space)
  }
  return valArry.join("");
}

I triggered it with the keyup event

Mar.01,2021

you need to remember the cursor position. After changing, reset the cursor position


<html>

<head>
    <meta charset="utf-8">
    <script>
  

    function Mobile(obj,e){
            if(e.keyCode == 8) return
            var value = obj.value;
            console.log(value)
            value = value.replace(/\s*/g, "");
            var result = [];
            for(var i = 0; i < value.length; iPP){
                if (i==3||i==7){
                    result.push(" " + value.charAt(i));
                }
                else{
                    result.push(value.charAt(i));
                }
            }
            obj.value = result.join("");
    }
    </script>
    <style>
        div{
            height: 100px;
            background: -sharpccc;
            vertical-align: center;
        }

    </style>
</head>

<body>
       <input type="tel" maxlength="13" id="mobile" onkeyup="Mobile(this,event)" onfocus="value=''" />
       <div>
           <input type="text">
       </div>
</body>
</html>

I tried to write. I think it meets your requirements. I modified the test on my side. No problem.


because you re-assigned the value to input when you were in keyup, the cursor will be located at the end.
go straight to the code.

  https://codepen.io/xiaoyi_122.

Menu