How to trigger onchange event with input element when click shortcut

Dear

I reproduce the issue with below link. Could you please have a look?
https://codepen.io/Stanley-549393092/pen/pozdQjZ?editors=1011

As you can see, there is a shortcut (ctrl+s) for the save button.
If I input something (E.g. xxx) and click the save button directly, the console log will be xxx.
However, if I change to yyy and click shortcut (ctrl+s), the console log will still be xxx unless I click enter.

So how to trigger onchange event? (maybe it is hard because the cursor is still on the input element).
Or is there any other solution to make sure the data is the newest before clicking shortcut. I can’t tell user that you have to click enter everytime before clicking shortcut(ctrl+s).

Best Regards,
Stanley

Remove .lazy.

<input v-model="text"/>

lazy makes v-model use the change event which isn’t triggered until the input loses focus. You want to use the default input event which is triggered on every character input.

More about modifiers: https://vuejs.org/v2/guide/forms.html#Modifiers

Hi James,

Thanks for your quick response.
Now I changed the source code to explains it more.
Yes, using v-model (without lazy modifier) can solve the problem because the data is in sync mode.
However, in some case (E.g. performance issue), I would like to use to call change event.
In this case, when you did some change and click save button, the data is the newest because the cursor is lost. However, if using shortcut to save data, the data is the old one.
Could you please look again?

Well, if you’re using the change event then the value won’t update until the input loses focus.

So you can either manually blur it: https://codepen.io/getreworked/pen/yLBPZdE?editors=1011

or you can debounce your input function so it doesn’t run the function every keystroke - though that could end up having timing issues so I’d probably go for blurring the input.

Thanks James.

It’s cool. Can we go it farther? Suppose there are a lot fields on the screen and I don’t want all the fields are attached with ref. My assumption is that all the fields are wrapped by form, so can I do something with the form? Or do you have some suggestion?
I updated the source code.
https://codepen.io/Stanley-549393092/pen/pozdQjZ?editors=1011

You can use document.activeElement to get the currently focused element.

saveText () {
  document.activeElement.blur();

  console.log('text1=' + this.text1)
  console.log('text2=' + this.text2)
  console.log('text3=' + this.text3)
}
1 Like

Hi James,

it’s unbelievable you made it.
Thank you so much for you help.