Tuesday, May 28, 2024
 Popular · Latest · Hot · Upcoming
0
rated 0 times [  3] [ 3]  / answers: 1 / hits: 27706  / 7 Years ago, thu, march 9, 2017, 12:00:00

I only started coding with vue.js yesterday, and I don't know how to focus on a textbox without using the traditional JS way, which is document.getElementById('myTextBox').focus().



Initially, my textbox is hidden. I have a Start button, and when the user clicks on it, the textbox is then displayed, and I want to set the focus there, so to speak. I already tried using ref, but to no avail (see code below).



HTML:



<input id=typeBox ref=typeBox placeholder=Type here... />


Javascript



export default {
name: 'game',

methods: {
startTimer () {
setTimeout(function () { /* .focus() won't work without this */

/* ugly and not recommended */
// document.getElementById('typeBox').focus()

/* Throws the error: Cannot read property 'typeBox' of undefined */
this.$refs.typeBox.focus()

// ... any other options?
// ...

}, 1)
}
} /* END methods */

} /* END export default */


Does anyone know how to do this? Please help.



UPDATE:



Adding autofocus on input does the trick of focusing right after the page is loaded. But in my app, there is a need to refocus on the input field several times without reloading the page, that's why I need a way to call .focus().


More From » vue.js

 Answers
103

Sharing the solution here just in case someone encounters the same problem...



I finally figured this out with the help of a senior programmer. I was also able to eliminate setTimeout along the way, using its vue version nextTick().



The correct JS code:



startTimer () {
this.$nextTick(() => {

// this won't work because `this.$refs.typeBox` returns an array
// this.$refs.typeBox.focus()

//this one works perfectly
this.$refs.typeBox[0].focus()

})
} /* END startTimer */


Explanation:



When I used console.log(this.$refs.typeBox), it returned this array:



enter



That's why for the code to work, it had to be typeBox[0].focus() instead of typeBox.focus().


[#58614] Tuesday, March 7, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
prestonh

Total Points: 384
Total Questions: 105
Total Answers: 105

Location: England
Member since Tue, Sep 8, 2020
4 Years ago
;