JNM
JNM

Reputation: 1195

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.

Upvotes: 3

Views: 2336

Answers (2)

Cecchi
Cecchi

Reputation: 1535

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();
}

Upvotes: 2

The Alpha
The Alpha

Reputation: 146249

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.

Upvotes: 1

Related Questions