3

Possible Duplicate:
jQuery Set Cursor Position in Text Area

When an input with text is focused, the cursor begins at the end of the text on the right side. How can I make the cursor locate at the left side on focus?

I've seen examples using "setCursor", but I get an error that setCursor is not defined.

<input type="text" class="myInput">
    Tabbing into this should put my cursor at the left!
</input>

setCursor throws an error that it's undefined.

$(".myInput").focus(function(){
    var node = $(this);
    setCursor(node, 0);
});
Community
  • 1
  • 1
Don P
  • 60,113
  • 114
  • 300
  • 432
  • It's close, but that question's answers were from 2009 so there are probably much cleaner ways to handle it now :) – Don P Nov 05 '12 at 04:02
  • _"When an input with text is focused, the cursor begins at the end of the text on the right side"_ - Doesn't it normally select all of the text in the input if tabbing in, or put the cursor exactly where you click if using the mouse? – nnnnnn Nov 05 '12 at 04:04
  • 3
    @DonnyP Actually I think nothing has changed regarding this, even with HTML5. – AndreKR Nov 05 '12 at 04:15

1 Answers1

3

Try this..

<input type="text" class="myInput" value="Tabbing into this should put my cursor at the left!" />

(function(){
        jQuery.fn.setSelection = function(selectionStart, selectionEnd) {
            if(this.length == 0) return this;
            input = this[0];

            if (input.createTextRange) {
                var range = input.createTextRange();
                range.collapse(true);
                range.moveEnd('character', selectionEnd);
                range.moveStart('character', selectionStart);
                range.select();
            } else if (input.setSelectionRange) {
                input.focus();
                input.setSelectionRange(selectionStart, selectionEnd);
            }

            return this;
        }
        jQuery.fn.setCursorPosition = function(position){
            if(this.length == 0) return this;
            return $(this).setSelection(position, position);
        }
        $(".myInput").focus(function(){
            $(this).setCursorPosition(0);
        });
    })();

Hopefully, it will be work now

Hasib Tarafder
  • 5,773
  • 3
  • 30
  • 44