jQuery Set Cursor Position in Text Area

前端 未结 16 1484
无人共我
无人共我 2020-11-21 11:42

How do you set the cursor position in a text field using jQuery? I\'ve got a text field with content, and I want the users cursor to be positioned at a certain offset when

16条回答
  •  醉话见心
    2020-11-21 12:26

    As for me here the most easily way to add text(Tab -> \t) in textarea by cursor position and save the focus on cursor:

    $('#text').keyup(function () {
        var cursor = $('#text').prop('selectionStart');
        //if cursot is first in textarea
        if (cursor == 0) {
            //i will add tab in line
            $('#text').val('\t' + $('#text').val());
            //here we set the cursor position
            $('#text').prop('selectionEnd', 1);
        } else {
            var value = $('#text').val();
            //save the value before cursor current position
            var valToCur = value.substring(0, cursor);
            //save the value after cursor current position
            var valAfter = value.substring(cursor, value.length);
            //save the new value with added tab in text
            $('#text').val(valToCur + '\t' + valAfter);
            //set focus of cursot after insert text (1 = because I add only one symbol)
            $('#text').prop('selectionEnd', cursor + 1);
        }
    });
    

提交回复
热议问题