I have a text box field in my simple HTML/JavaScript-based form where users can insert variables, as shown in the example below:
The name of the product is ${productName}
When the user submits the form, a JavaScript function replaces the variable with its actual product value.
I’d like to implement a feature where, if the user places their cursor to the right of the variable ${productName}
and presses the backspace key, the entire variable is deleted in one go, instead of deleting each character one at a time. Placing the cursor in the middle of variable text should not do anything. User shouldnt be allowed to delete individual character of the variable and/or add characters. Essentially, I want the variable to behave as a single, indivisible entity in the text box.
I’m unsure what the technical term for this feature is or how to start researching it. What’s the most efficient way to implement this behaviour?
2
Answers
Simple example, you should judge for yourself whether it’s efficient enough.
On keydown of backspace (as long as no text is selected), we get the part of the text before the cursor and see if it ends in ${myvar}. If so we figure out the length of ${myvar} and remove that much from the text. Then we set the cursor to its new position.
Here is an attempt to implement the rules:
This code does not itself mutate the value. It merely changes the selection of the text upon which the key will act. That way the undo/redo mechanism will continue to work as expected.