Juicy
Juicy

Reputation: 12530

Auto-focus input box in toggleable text/input fields

I'm building a "toggleable" form where I would like <p> tags to become <input> tags on click.

The following JSFiddle does that: https://jsfiddle.net/50wL7mdz/314578/

The main bit is as follows:

<div id="app">
  <div v-for="msg in messages" :key="msg.txt">
    <div :class="{editing: msg.edit}">
      <p v-on:click="msg.edit = !msg.edit">{{msg.txt}}</p>
      <input type="text" v-model="msg.txt">
    </div>
  </div>
</div>

For a good user experience I would like the <input> boxes to be focused when they are un-hidden, so the user can start typing right away.

My problem is slightly complicated by the fact that I can't predict how many input fields will be in the form (as you can see from the JSFiddle, I've generated the groups with a for loop).

How can I set the focus to newly unveiled <input> boxes?

Upvotes: 1

Views: 49

Answers (1)

ExohJosh
ExohJosh

Reputation: 1892

https://jsfiddle.net/50wL7mdz/314662/

<div v-for="(msg, index) in messages" :key="msg.txt">
    <div :class="{editing: msg.edit}">
      <p v-on:click="toggle(index, $event)">{{msg.txt}}</p>
      <input type="text" v-model="msg.txt">
    </div>
  </div>

toggle(index, event) {
      this.messages[index].edit = !this.messages[index].edit
            this.$nextTick(function(){
        event.target.parentNode.querySelector('input').focus()
      });
    }

Try this one mate - You can expose the event in Vue by passing $event in your on-click binding, then we just check the target of the click, find the sibling input and focus it AFTER Vue has done it's nextTick (When the component has re-rendered, in this case and the text box is visible)

Enjoy!

Upvotes: 3

Related Questions