Inserting a text where cursor is using Javascript/jquery

前端 未结 13 2679
盖世英雄少女心
盖世英雄少女心 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:34

    The code above didn't work for me in IE. Here's some code based on this answer.

    I took out the getElementById so I could reference the element in a different way.

    function insertAtCaret(element, text) {
      if (document.selection) {
        element.focus();
        var sel = document.selection.createRange();
        sel.text = text;
        element.focus();
      } else if (element.selectionStart || element.selectionStart === 0) {
        var startPos = element.selectionStart;
        var endPos = element.selectionEnd;
        var scrollTop = element.scrollTop;
        element.value = element.value.substring(0, startPos) +
          text + element.value.substring(endPos, element.value.length);
        element.focus();
        element.selectionStart = startPos + text.length;
        element.selectionEnd = startPos + text.length;
        element.scrollTop = scrollTop;
      } else {
        element.value += text;
        element.focus();
      }
    }
    input{width:100px}
    label{display:block;margin:10px 0}
    
    
    

    EDIT: Added a running snippet, jQuery is not being used.

提交回复
热议问题