Ie11 Moves Cursor To Beginning Of Input When Editing Value
I have a really odd problem on a project. Long Story Short, I have input fields that record interest rate, so a % is appended on blur and removed on focus. It works fine on every
Solution 1:
You could try to set caret position manually when appending/removing %
mark, using those two functions (those are pretty generic and should work for every browser if you need setting caret positions for all browsers some other time):
function getCaretPosition(element) {
var caretPos = 0;
if (element.type === 'text' || element.type === 'tel') {
if (document.selection) { // IE Support
element.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -element.value.length);
caretPos = Sel.text.length;
} elseif (element.selectionStart || element.selectionStart === '0') {// Firefox support
caretPos = element.selectionStart;
}
}
return caretPos;
}
function setCaretPosition(element, position) {
if (element.type === 'text' || element.type === 'tel') {
if (element.setSelectionRange) {
element.focus();
element.setSelectionRange(position, position);
} elseif (element.createTextRange) {
varrange = element.createTextRange();
range.collapse(true);
range.moveEnd('character', position);
range.moveStart('character', position);
range.select();
}
}
}
And call them only when using IE11 :) Also, if you want, you could make those functions more specific, removing parts for FF :)
Solution 2:
This issue can be solved by:
- getting a reference to the input element
- adding an
onfocus
event handler
Then setting the selection range in the onfocus
handler to the end of the input value, like so:
constonFocus = (el) => {
const { value } = el.value
el.setSelectionRange(value.length, value.length);
}
<input type='text' onfocus='onFocus(this)' />
If you are using ReactJS, here is that solution.
Post a Comment for "Ie11 Moves Cursor To Beginning Of Input When Editing Value"