Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript focus remove text highlight

I have an input (text field) in update panel, and it autopostbacks after each change of text. I can keep focus on the same text field, but i can't get rid of text higlight which appears after calling document.getElementById('myTextField').focus(). This solution seemed to be the most accurate:

if (window.getSelection) {
    window.getSelection().removeAllRanges();
} else if (document.selection) {
    document.selection.empty();
}

But it has one problem. Input remains focused, but i can't write text. I have to click on it before writing.

like image 594
JNM Avatar asked Jan 24 '26 10:01

JNM


2 Answers

I'd argue that an ideal solution wouldn't involve unsetting and resetting the value of the input. This could have unwanted side-effects. Here's the proper way to move the caret in my opinion:

var input = document.getElementById('inputElement');
input.focus();
if(input.setSelectionRange) {
  input.setSelectionRange(input.value.length, input.value.length);
} else {
  var range = input.createTextRange();
  range.moveStart('character', input.value.length);
  range.moveEnd('character', input.value.length);
  range.select();
}
like image 105
Cecchi Avatar answered Jan 26 '26 00:01

Cecchi


You can do it if you reset your value after focus, i.e.

HTML

<input id="myTextField" type="text" value="SomeValue" />​

JS

var myInput=document.getElementById('myTextField');
var myInput_value=myInput.value;
myInput.focus();
myInput.value=myInput_value;​

Working Example.

like image 29
The Alpha Avatar answered Jan 26 '26 00:01

The Alpha