Skip to content
Snippets Groups Projects
Verified Commit 399050c4 authored by Jonathan Weth's avatar Jonathan Weth :keyboard:
Browse files

Add support for backspaces, tabs and arrow keys to make them work as expected

parent 5a6c4d57
1 merge request!8Draft: Resolve "Add support for backspaces, tabs and arrow keys"
console.log("Input script loaded");
const KEY_CODES_TAB = [9, 16];
const KEY_CODE_ARROW_LEFT = 37;
const KEY_CODE_ARROW_RIGHT = 39;
const KEY_CODE_BACKSPACE = 8;
$(document).ready(function () {
let all_inputs = $(".split-input-group input");
console.log("Split inputs loaded.")
......@@ -15,9 +20,27 @@ $(document).ready(function () {
let target = $(e.target);
let value = target.val();
let max_len = target.attr("maxLength");
if (value.length >= max_len) {
let cursorPosition = target.get(0).selectionStart;
// Detect some special key codes to sort them out later
let isTabEvent = KEY_CODES_TAB.includes(e.keyCode);
let isKeyArrowLeftEvent = e.keyCode === KEY_CODE_ARROW_LEFT;
let isKeyArrowRightEvent = e.keyCode === KEY_CODE_ARROW_RIGHT
let isKeyArrowEvent = isKeyArrowLeftEvent | isKeyArrowRightEvent;
let isBackspaceEvent = e.keyCode === KEY_CODE_BACKSPACE;
if ( // Go to next input ...
(value.length >= max_len && !isTabEvent && !isKeyArrowEvent) // ... if maximum length is reached and it wasn't an arrow key or tab
|| (cursorPosition === value.length && isKeyArrowRightEvent) // ... or, if the user presses arrow right when the cursor is at the end of the input
) {
target.next("input.split-input").focus();
console.log("Next target selected");
} else if ( // Go to previous input ...
(value.length === 0 && isBackspaceEvent) // ... if the complete input is empty and the user presses backspace
|| (cursorPosition === 0 && isKeyArrowLeftEvent) /// ... or, if the user presses arrow left when the cursor is at the beginning of the input
) {
target.prev("input.split-input").focus();
console.log("Prev target selected");
}
})
})
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment