I'm trying to detect when the user is pressing the tab key, so I can insert spaces, instead of shifting the element focus.
The event handler is called correctly, but the value of both .selectionStart and .selectionEnd properties are either undefined or NaN. Is there something wrong with my code?
<b-form-textarea
id="pythonCodeInput"
placeholder="Write Python code here..."
v-model="newQuestion.objects.code"
ref="codeInput"
@keydown.native.tab="keyDownInTextarea">
</b-form-textarea>
Relevant code from keyDownInTextarea
let codeInput = this.$refs.codeInput;
// Add 4 spaces
let tabSize = 4;
let tabPosition = codeInput.selectionStart;
let textWithSpaces = codeInput.value.substring(0, tabPosition);
for (let i = 0; i < tabSize; i++) textWithSpaces += " ";
textWithSpaces += codeInput.value.substring(tabPosition);
I expect tabPosition to have an value showing where the cursor is, but the actual output is NaN or undefined.
When you attached a ref
to <b-form-textarea>
, what you get is the reference to an instance of the <b-form-textarea>
component and not the textarea
element which you are trying to access. Refer to
docs for more info.
To access the actual <textarea>
element, you can do it by accessing the inner $refs
of your codeInput
ref since under the hood, the textarea
element has a ref called input
.
To put it simply, it would look like this.
// this is a reference to the `<b-form-textarea>` component instance.
let codeInput = this.$refs.codeInput;
// get the actual DOM element
const textArea = codeInput.$refs.input;
See working example