I have many inputs fields which I need to fill repeatedly so I usually use Tab to navigate through the form.
Fields have default suffix value which needs to be prepended. It works as expected when I focus in the input with mouse click.
However when I tab between inputs it selects all text which is undesirable behaviour in my case.
Have a look at this:
function setCaretPosition(elem, caretPos) {
if (elem == null) return;
if (elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
} else if (elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
} else {
elem.focus();
}
}
$(document).ready(function() {
$('input').focus(function() {
setCaretPosition(this, 0);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1" value=" km/h" />
<input type="text" id="input2" value=" kg" />
- When you click inside any of the inputs, caret is set at the beginning.
- When you Tab between inputs caret is not set. Instead, whole input contents is higlighted.
How do I prevent text input from higlighting its contents when using tab navigation?
I prefer the answer without use of setTimeout
(if it's possible at all).