Home  >  Q&A  >  body text

How do I set focus on a newly (auto)rendered dom element?

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粉821274260P粉821274260190 days ago475

reply all(2)I'll reply

  • P粉459440991

    P粉4594409912024-03-31 20:04:17

    (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