Caret position on jquery input focus()
sprutgaming opened this issue · 5 comments
$("input").inputmask('decimal', {
"autoUnmask": true,
'allowMinus': false,
'placeholder': '0',
'max': 24,
'min': 0,
'digits': 0,
'suffix': ' h',
'numericInput': true,
});
$("input").focus();
When the page loads, the input field is focused programmatically through the jquery - focus() method. The caret position is always placed before the number.
How can I force the caret to position between a number and the suffix "h"?
It was also assumed that when you click after the suffix “h”, the caret will move in front of the suffix, like this:
Use the positionCaretOnClick
option with the value radixFocus
. This way it will always place the caret after the numeric value in you case since you have the decimal
alias with no decimal places. You can also set it none
if you want to position the caret where you clicked just like in a regular text input.
Okey, but I added several letter symbols to the mask. I also added it according to your recommendation, but the result remained the same, the caret is placed on the left side of the number
$("input").inputmask('decimal', { 'mask':['99','N','n','G','g','F','f'], "autoUnmask": true, 'allowMinus': false, 'placeholder': '0', 'max': 24, 'min': 0, 'digits': 0, 'positionCaretOnClick': 'radixFocus', 'numericInput': true, });
I also want to clarify that to focus on the field, I use the focus() method of jquery:
$("input").focus();
I'm afraid this is not possible with just triggering focus from an external source. There is a workaround - if you know the length of your numeric value, you can set selectionStart
property of the input field and then focus it like this:
$("#field")[0].selectionStart = 1; //assuming there is one digit in the field
$("#field").focus();
I am posting a working solution to my problem:
Since I use the tippy library to display the input field, and I have Input inside the tooltip, the following code worked:
$(this).inputmask('decimal', {
'mask':['9{1,}','N','n','G','g'],
"autoUnmask": true,
'allowMinus': false,
'placeholder': '0',
'max': 24,
'min': 0,
'digits': 0,
'positionCaretOnClick': 'radixFocus',
'numericInput': true,
});
In the tippy library you need to specify the code in the function onShown()
:
onShown() {
let input = $("input.tippy-input");
input[0].selectionStart = input.val().length;
input.focus();
}
This design works in my case, but I just need to remember to initiate the Inputmask at the right time:
const observer = new MutationObserver(function (mutationsList) {
mutationsList.forEach(function (mutation) {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
$(mutation.addedNodes).find('input');
}
});
});
@Techn1c4l Thanks a lot!
Maybe this could help with the alignment.
https://robinherbots.github.io/Inputmask/#/documentation#rightalign