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

Community
  • 1
  • 1
Arian
  • 12,793
  • 66
  • 176
  • 300

2 Answers2

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" />
Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
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/

Heavy
  • 1,861
  • 14
  • 25