Inserting text after cursor position in text area

后端 未结 3 358
闹比i
闹比i 2020-12-10 14:04

The script below inserts text to the end of text area. I need to change to insert text after current cursor position in the text area.

jQuery(document).read         


        
3条回答
  •  隐瞒了意图╮
    2020-12-10 14:29

    if the above does not work (it didn't in my case - maybe my configuration is little bit different), here is another solution:

    you can use this extension function to get the position:

    (function ($, undefined) {
        $.fn.getCursorPosition = function () {
            var el = $(this).get(0);
            var pos = 0;
            if ('selectionStart' in el) {
                pos = el.selectionStart;
            } else if ('selection' in document) {
                el.focus();
                var Sel = document.selection.createRange();
                var SelLength = document.selection.createRange().text.length;
                Sel.moveStart('character', -el.value.length);
                pos = Sel.text.length - SelLength;
            }
            return pos;
        }
    })(jQuery);
    

    the usage is : var position = $("#selector").getCursorPosition()

    to insert text at the position:

    var content = $('#selector').val();
    var newContent = content.substr(0, position) + "text to insert" + content.substr(position);
    $('#selector').val(newContent);
    

    That's all.

提交回复
热议问题