How do I set focus on a newly (auto)rendered dom element?
P粉821274260
P粉821274260 2024-03-30 23:59:45
0
2
469

I have an input field that automatically replaces with a text area and the same content based on the number of characters entered by the user:

<textarea v-if="myString.length > 20" v-model="myString"/>
<input type="text" v-if="myString.length <= 20" v-model="myString"/>

The problem I have is that the focus is lost when the user enters the 21st character. Therefore, the user gets annoyed because when he types the 22nd character, the character does not appear in the text area (has no focus). How can I set focus on the newly rendered text area? The problem here is that it renders automatically. Otherwise I can set a reference on the textarea and call focus().

Another problem is removing the 21st character and switching back from the textarea to the input element.

P粉821274260
P粉821274260

reply all(2)
P粉459440991

(Copy my comment as this may be helpful)

Replacing input elements with textarea may produce a poor user experience. Why not just use textarea from the beginning? If you want the style to change based on the input length, for example increasing the height if it's more than 20 characters, then you can do that using CSS.

sssccc



Demo (forked from @tony19)

P粉333186285

You can wrap the textarea/input in a component and use its mounted hook to call its focus(), As shown in the following components:


sssccc




Demo

While this is technically possible, this user experience may not be ideal, and you should consider other designs that don't require centralized input like this (as @kien_coi_1997 suggests).

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!