1

Using this topic: jQuery Set Cursor Position in Text Area

I write this code but it does not works:

<input id="myTextInput" type="text" value="some text2">
<input type="button" value="set mouse" id="btn" />

and:

$(document).ready(function () {
    $('#btn').on('click', function () {
        var inp = $('#myTextInput');        
        var pos = 3;
        inp.focus();
        if (inp.setSelectionRange) {
            inp.setSelectionRange(pos, pos);
        } else if (inp.createTextRange) {
            var range = inp.createTextRange();
            range.collapse(true);
            if (pos < 0) {
                pos = $(this).val().length + pos;
            }
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    });
});

DEMO

Where is my mistake? Thanks

1
  • the correct search term is caret Commented Nov 6, 2014 at 7:29

2 Answers 2

2

Your mistake is that you select the jQuery object instead of DOM element: replace var inp = $('#myTextInput'); with var inp = $('#myTextInput')[0];.

JSFIDDLE


However, I'd recommend using the plugin from this answer, since the code will look cleaner:

$.fn.selectRange = function(start, end) {
  return this.each(function() {
    if (this.setSelectionRange) {
      this.focus();
      this.setSelectionRange(start, end);
    } else if (this.createTextRange) {
      var range = this.createTextRange();
      range.collapse(true);
      range.moveEnd('character', end);
      range.moveStart('character', start);
      range.select();
    }
  });
};


$(document).ready(function() {
  $('#btn').on('click', function() {
    var pos = 7;
    $('#myTextInput').focus().selectRange(pos, pos);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myTextInput" type="text" value="some text2">
<input type="button" value="set mouse" id="btn" />

Sign up to request clarification or add additional context in comments.

Comments

0

You need DOM element rather than JQuery object to use setSelectionRange or createTextRange. Use .get(0) to retreive it.

var inp = $('#myTextInput');
inp.focus();
inp = inp.get(0);

http://jsfiddle.net/qeanb8gk/1/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.