jQuery Set Cursor Position in Text Area

前端 未结 16 1488
无人共我
无人共我 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:17

    I do realize that this is a very old post, but I thought that I should offer perhaps a simpler solution to update it using only jQuery.

    function getTextCursorPosition(ele) {   
        return ele.prop("selectionStart");
    }
    
    function setTextCursorPosition(ele,pos) {
        ele.prop("selectionStart", pos + 1);
        ele.prop("selectionEnd", pos + 1);
    }
    
    function insertNewLine(text,cursorPos) {
        var firstSlice = text.slice(0,cursorPos);
        var secondSlice = text.slice(cursorPos);
    
        var new_text = [firstSlice,"\n",secondSlice].join('');
    
        return new_text;
    }
    

    Usage for using ctrl-enter to add a new line (like in Facebook):

    $('textarea').on('keypress',function(e){
        if (e.keyCode == 13 && !e.ctrlKey) {
            e.preventDefault();
            //do something special here with just pressing Enter
        }else if (e.ctrlKey){
            //If the ctrl key was pressed with the Enter key,
            //then enter a new line break into the text
            var cursorPos = getTextCursorPosition($(this));                
    
            $(this).val(insertNewLine($(this).val(), cursorPos));
            setTextCursorPosition($(this), cursorPos);
        }
    });
    

    I am open to critique. Thank you.

    UPDATE: This solution does not allow normal copy and paste functionality to work (i.e. ctrl-c, ctrl-v), so I will have to edit this in the future to make sure that part works again. If you have an idea how to do that, please comment here, and I will be happy to test it out. Thanks.

提交回复
热议问题