Inserting a text where cursor is using Javascript/jquery

前端 未结 13 2666
盖世英雄少女心
盖世英雄少女心 2020-11-22 03:58

I have a page with a lot of textboxes. When someone clicks a link, i want a word or two to be inserted where the cursor is, or appended to the textbox which has the focus.<

相关标签:
13条回答
  • 2020-11-22 04:19

    The accepted answer didn't work for me on Internet Explorer 9. I checked it and the browser detection was not working properly, it detected ff (firefox) when i was at Internet Explorer.

    I just did this change:

    if ($.browser.msie) 
    

    Instead of:

    if (br == "ie") { 
    

    The resulting code is this one:

    function insertAtCaret(areaId,text) {
        var txtarea = document.getElementById(areaId);
        var scrollPos = txtarea.scrollTop;
        var strPos = 0;
        var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? 
            "ff" : (document.selection ? "ie" : false ) );
    
        if ($.browser.msie) { 
            txtarea.focus();
            var range = document.selection.createRange();
            range.moveStart ('character', -txtarea.value.length);
            strPos = range.text.length;
        }
        else if (br == "ff") strPos = txtarea.selectionStart;
    
        var front = (txtarea.value).substring(0,strPos);  
        var back = (txtarea.value).substring(strPos,txtarea.value.length); 
        txtarea.value=front+text+back;
        strPos = strPos + text.length;
        if (br == "ie") { 
            txtarea.focus();
            var range = document.selection.createRange();
            range.moveStart ('character', -txtarea.value.length);
            range.moveStart ('character', strPos);
            range.moveEnd ('character', 0);
            range.select();
        }
        else if (br == "ff") {
            txtarea.selectionStart = strPos;
            txtarea.selectionEnd = strPos;
            txtarea.focus();
        }
        txtarea.scrollTop = scrollPos;
    }
    
    0 讨论(0)
  • 2020-11-22 04:19

    Content Editable, HTML or any other DOM element Selections

    If you are trying to insert at caret on a <div contenteditable="true">, this becomes much more difficult, especially if there are children within the editable container.

    I have had really great luck using the Rangy library:

    • GIT: https://github.com/timdown/rangy
    • NPM: https://www.npmjs.com/package/rangy

    It has a ton of great features such as:

    • Save Position or Selection
    • Then later, Restore the Position or Selection
    • Get selection HTML or Plaintext
    • Among many others

    The online demo was not working last I checked, however the repo has working demos. To get started, simple download the Repo from Git or NPM, then open ./rangy/demos/index.html

    It makes working with caret pos and text selection a breeze!

    0 讨论(0)
  • 2020-11-22 04:20

    Use this, from here:

    function insertAtCaret(areaId, text) {
      var txtarea = document.getElementById(areaId);
      if (!txtarea) {
        return;
      }
    
      var scrollPos = txtarea.scrollTop;
      var strPos = 0;
      var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
        "ff" : (document.selection ? "ie" : false));
      if (br == "ie") {
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart('character', -txtarea.value.length);
        strPos = range.text.length;
      } else if (br == "ff") {
        strPos = txtarea.selectionStart;
      }
    
      var front = (txtarea.value).substring(0, strPos);
      var back = (txtarea.value).substring(strPos, txtarea.value.length);
      txtarea.value = front + text + back;
      strPos = strPos + text.length;
      if (br == "ie") {
        txtarea.focus();
        var ieRange = document.selection.createRange();
        ieRange.moveStart('character', -txtarea.value.length);
        ieRange.moveStart('character', strPos);
        ieRange.moveEnd('character', 0);
        ieRange.select();
      } else if (br == "ff") {
        txtarea.selectionStart = strPos;
        txtarea.selectionEnd = strPos;
        txtarea.focus();
      }
    
      txtarea.scrollTop = scrollPos;
    }
    <textarea id="textareaid"></textarea>
    <a href="#" onclick="insertAtCaret('textareaid', 'text to insert');return false;">Click Here to Insert</a>

    0 讨论(0)
  • 2020-11-22 04:22

    The approved answer from George Claghorn worked great for simply inserting text at the cursor position. If the user had selected text though, and you want that text to be replaced (the default experience with most text), you need to make a small change when setting the 'back' variable.

    Also, if you don't need to support older versions of IE, modern versions support textarea.selectionStart, so you can take out all of the browser detection, and IE-specific code.

    Here is a simplified version that works for Chrome and IE11 at least, and handles replacing selected text.

    function insertAtCaret(areaId, text) {
        var txtarea = document.getElementById(areaId);
        var scrollPos = txtarea.scrollTop;
        var caretPos = txtarea.selectionStart;
    
        var front = (txtarea.value).substring(0, caretPos);
        var back = (txtarea.value).substring(txtarea.selectionEnd, txtarea.value.length);
        txtarea.value = front + text + back;
        caretPos = caretPos + text.length;
        txtarea.selectionStart = caretPos;
        txtarea.selectionEnd = caretPos;
        txtarea.focus();
        txtarea.scrollTop = scrollPos;
    }
    
    0 讨论(0)
  • 2020-11-22 04:23

    How to insert some Text to current cursor position of a TextBox through JQuery and JavaScript

    Process

    1. Find the Current Cursor Position
    2. Get the Text to be Copied
    3. Set the Text Over there
    4. Update the Cursor position

    Here I have 2 TextBoxes and a Button. I have to Click on a certain position on a textbox and then click on the button to paste the text from the other textbox to the the position of the previous textbox.

    Main issue here is that getting the current cursor position where we will paste the text.

    //Textbox on which to be pasted
    <input type="text" id="txtOnWhichToBePasted" />
    
    //Textbox from where to be pasted
    <input type="text" id="txtFromWhichToBePasted" />
    
    
    //Button on which click the text to be pasted
    <input type="button" id="btnInsert" value="Insert"/>
    
    
    <script type="text/javascript">
    
    $(document).ready(function () {
        $('#btnInsert').bind('click', function () {
                var TextToBePasted = $('#txtFromWhichToBePasted').value;
                var ControlOnWhichToBePasted = $('#txtOnWhichToBePasted');
    
                //Paste the Text
                PasteTag(ControlOnWhichToBePasted, TextToBePasted);
            });
        });
    
    //Function Pasting The Text
    function PasteTag(ControlOnWhichToBePasted,TextToBePasted) {
        //Get the position where to be paste
    
        var CaretPos = 0;
        // IE Support
        if (document.selection) {
    
            ControlOnWhichToBePasted.focus();
            var Sel = document.selection.createRange();
    
            Sel.moveStart('character', -ctrl.value.length);
    
            CaretPos = Sel.text.length;
        }
        // Firefox support
        else if (ControlOnWhichToBePasted.selectionStart || ControlOnWhichToBePasted.selectionStart == '0')
            CaretPos = ControlOnWhichToBePasted.selectionStart;
    
        //paste the text
        var WholeString = ControlOnWhichToBePasted.value;
        var txt1 = WholeString.substring(0, CaretPos);
        var txt2 = WholeString.substring(CaretPos, WholeString.length);
        WholeString = txt1 + TextToBePasted + txt2;
        var CaretPos = txt1.length + TextToBePasted.length;
        ControlOnWhichToBePasted.value = WholeString;
    
        //update The cursor position 
        setCaretPosition(ControlOnWhichToBePasted, CaretPos);
    }
    
    function setCaretPosition(ControlOnWhichToBePasted, pos) {
    
        if (ControlOnWhichToBePasted.setSelectionRange) {
            ControlOnWhichToBePasted.focus();
            ControlOnWhichToBePasted.setSelectionRange(pos, pos);
        }
        else if (ControlOnWhichToBePasted.createTextRange) {
            var range = ControlOnWhichToBePasted.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    }
    
    </script>
    
    0 讨论(0)
  • 2020-11-22 04:28

    using @quick_sliv answer:

    function insertAtCaret(el, text) {
        var caretPos = el.selectionStart;
        var textAreaTxt = el.value;
        el.value = textAreaTxt.substring(0, caretPos) + text + textAreaTxt.substring(caretPos);
    };
    
    0 讨论(0)
提交回复
热议问题