In my application, I am aiming to create a user experience similar to Microsoft Excel / Google Sheets where there is an autocomplete dropdown for formulas and variables. Once the autocomplete has been validated, I want to have control over the cursor position.
For example, if I enter =sum(variable1, variable2), when selecting variable2 from the autocomplete, I want the cursor to appear before the last parenthesis rather than at the very end.
I know how to adjust the cursor position using JavaScript, but the issue arises when I try to modify the input value and set the cursor position simultaneously - it doesn't seem to work properly.
I've replicated the problem on a simpler scale on fiddle: https://jsfiddle.net/joparisot/j8ourfa1/31/
Here is the HTML code snippet:
<div id="app">
<autocomplete v-model="selection"></autocomplete>
</div>
<template id="autocomplete">
<div>
<h2>gernerogrnio</h2>
<input id="my-input"
class="form-control"
type="text"
:value="value"
@keydown.enter="updateValue($event.target.value)">
<p>{{ value }}</p>
</div>
</template>
And here is the script section:
Vue.component('autocomplete', {
template: '#autocomplete',
props: {
value: {
type: String,
required: true
}
},
methods: {
updateValue (value) {
var new_value = ''
if (value.length < 4) {
new_value = 'Inferior'
} else {
new_value = 'Superior'
}
this.$emit('input', new_value)
var myInput = document.getElementById('my-input');
this.setCaretPosition(myInput, 5)
},
setCaretPosition(ctrl, pos) {
ctrl.focus();
ctrl.setSelectionRange(pos, pos);
}
}
});
new Vue({
el: '#app',
data: {
selection: 'test'
}
});
The focus here is not on the autocomplete functionality, but rather on adjusting the input value after pressing enter. You'll notice that setting the cursor position will work if you comment out lines 11 to 16 and simply assign the new_value to the existing value.
I'm struggling to achieve both tasks simultaneously. Any insights?