Input cursor jumps to end of input field on input event
If you (or Vue) copy a new value into an input, the cursor will be set to the end of the input. If you want to retain the previous position, you will need to capture the position, make the change, then on the $nextTick
restore the position.
Also note that if you are going to set this.input
in the handler, there's no point in your using v-model
, too. It's also unlikely that saving the event
is sensible, but you can.
new Vue({
el: "#app",
data() {
return {
input: null,
event: null
}
},
methods: {
handleInput(e) {
const el = e.target;
const sel = el.selectionStart;
const upperValue = el.value.toUpperCase();
el.value = this.input = upperValue;
this.event = e;
this.$nextTick(() => {
el.setSelectionRange(sel, sel);
});
}
}
});
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
input {
margin-bottom: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input type="text" @input="handleInput">
<p>{{ event ? event.target.value : null }}</p>
<p>
{{input}}
</p>
</div>