简体   繁体   中英

Set cursor within text of input using jQuery

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

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" /> 

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM