Chinese version is here: CSDN Version
This is the code of mine that has some problems.
I want to split every five letters with a space.
It does well if you enter or delete at the end of the input BUT when you enter or delete NOT at the end of the input, the cursor would automatically go to the end.
For instance, the textbox now have ABCDE FGHJK
. If I delete the A
, the cursor would go the end after deleting the A
.
let Input = document.createElement("input");
Input.setAttribute("type", "text");
Input.style.width = "100%";
Input.style.height = "30px";
Input.style.fontSize = "20px";
// The code AFTER this need modification and improvement
Input.addEventListener("input", function(e) {
Input.value = Input.value.replace(/s*/g,"");
Input.value = Input.value.replace(/(.{5})/g, '$1 ');
Input.value = Input.value.trim();
});
// The code BEFORE this need modification and improvement
document.body.appendChild(Input);
How to fix the code to prevent it? (It should ONLY include original Javascript code but NOT CSS, HTML code or Jquery.)
I’ve tried to relocate the cursorPosition
but it doesn’t work…
I would appreciate that if the code is as succinct as possible.
Remember the goal is to make the input as convenient as possible.
Some examples here (|
is the cursor):
Original Input | Operation | Result |
---|---|---|
ABCD|E FGHJK |
Enter X |
ABCDX| EFGHJ K |
ABCDE| FGHJK |
Enter X |
ABCDE X|FGHJ K |
ABCDE |FGHJK |
Enter X |
ABCDE X|FGHJ K |
ABCD|E FGHJK |
Backspace | ABC|EF GHJK |
ABCDE F|GHJK |
Backspace | ABCDE| GHJK or ABCDE |GHJK (You can choose either) |
ABCDE |FGHJK |
Backspace | ABCD|E FGHJK or ABCDE| FGHJK (You can choose either) |
ABC|DE FGHJK |
Enter Space |
ABC|DE FGHJK (no change) |
2
Answers
Modified your code a bit to restore cursor position:
You may try this: