I want to select a text area when I press '/' but when I do that it does it but also puts the slash in the box which I don't want.
document.addEventListener("keydown", e => {
if (e.key === '/') document.getElementById("box").select()
});
I've tried select, focus, and click. It selects the input text area, but it puts the slash as well.
CodePudding user response:
Just use keyup
instead:
document.addEventListener("keyup", e => {
if (e.key === '/') document.getElementById("box").select()
});
Edit:
Reason: The KeyboardEvent.key
event follows a sequence in the execution of the different types of events:
- keydown
- beforeinput (only on editable content like
<input>
,<textarea>
, etc.) - input (only on editable content like
<input>
,<textarea>
, etc.) - keyup
See KeyboardEvent sequence for further details.
So the thing that happens when using keydown
in your scenario is:
- keydown:
box
gets selected - beforeinput: fires because the active element is an editable element
- input: fires because the active element is an editable element inserting the
/
intobox
- keyup: nothing
When using keyup
instead:
- keydown: nothing
- beforeinput: doesn't fire because the active element is NOT an editable element
- input: doesn't fire because the active element is NOT an editable element
- keyup:
box
gets selected
Edit: If you want to be able to use /
inside the box
, first check that box
is not the active element:
document.addEventListener("keyup", e => {
const box = document.getElementById("box")
if (e.key === '/' && box !== document.activeElement) box.select()
});
CodePudding user response:
Using your listener like this would select the input field every time a user presses the "/"-Key
you should add "e.preventDefault()" to avoid displaying the character in the field.
document.addEventListener("keydown", e => {
e.preventDefault();
if (e.key === '/') document.getElementById("box").select()
[...]/* Logic here if you want the slash as a valid character */
});
CodePudding user response:
You could use an event listener to monitor the textarea for the character, and if it's detected, replace it with an empty string. Of course, this will prevent anyone from actually typing that character in the field as well, but it sounds like that might be what you want.
Example:
let textArea = document.getElementById("textArea");
// listen for keyup, if slash pressed, select text
textArea.addEventListener("keyup", (e) => {
if (e.key === "/") {
textArea.select();
}
});
// listen for input, replace slash with empty string
textArea.addEventListener("input", (e) => {
textArea.value = textArea.value.replaceAll("/", "");
})
<textarea rows="3" id="textArea">
</textarea>
CodePudding user response:
document.addEventListener("keydown", e => {
if (e.key === '/'){
e.preventDefault();
document.getElementById("box").select();
}
});