0

i'm having a textbox where i need to set focus/ cursor at required index of the textbox in opera browser.

kangax
  • 38,898
  • 13
  • 99
  • 135
Santhosh
  • 19,616
  • 22
  • 63
  • 74

2 Answers2

0

Working Demo

function SetCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        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();
        }
    }
}

elemId: id of the element

caretPos: position of the cursor

rahul
  • 184,426
  • 49
  • 232
  • 263
0

ur code works fine, but getting clash in opera.

becoz the following code snippet

if(elem.createTextRange) {

is also true to opera, but createTextRange 'll only supported by IE.

So i have changed little modification in ur code

function SetCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if (elem != null) {
        if ($.browser.msie) {
            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();
        }
    }
}
Santhosh
  • 19,616
  • 22
  • 63
  • 74
  • If you reverse the detection and look for elem.selectionStart first you don't need to use browser detection - always best practise :) – hallvors Oct 06 '09 at 16:58
  • (And Opera has limited support for createTextRange() and the rest of the IE selection API. We'll remove it again because it's incomplete - it's basically my fault for thinking all those years ago that the subset of functionality I wrote tests for was sufficient..) – hallvors Oct 06 '09 at 16:59