Add a string at the input and textarea cursors

Posted by Brendan Nolan on Tue, 15 Feb 2022 02:58:39 +0100

1, Reference

  1. setSelectionRange() reference

2, Problem description

Business requirements: if the camera hair has illegal parking, it needs to send a text message to the relevant car owners

Development task: relevant SMS templates need to be edited in advance, such as time, license plate number, owner's name and other general template information. Specific characters need to be used instead to facilitate background analysis. These strings are developed and have no practical significance for those who write SMS templates

3, Quick start

<html>
  <head> </head>
  <script type="text/javascript">
    function add(str) {
      var tc = document.getElementById("mytextarea");
      var tclen = tc.value.length;
      tc.focus();
      // compatibility check 
      if (typeof document.selection != "undefined") {
        document.selection.createRange().text = str;
      } else {
        tc.value =
          // Gets the start position of the cursor
          tc.value.substr(0, tc.selectionStart) +
          str +
          tc.value.substring(tc.selectionStart, tclen);
      }
    }
  </script>
  <body>
    <textarea rows="5" name="s1" cols="27" id="mytextarea">
Purpose by clicking the button on the page button stay textarea Insert text where the cursor stays in the </textarea
    >

    <ul>
      <li>
        <button onclick="add('huangbiao')">Add specified string</button>
      </li>
    </ul>
  </body>
</html>

4, Introduction to built-in objects

HTMLInputElement introduction

  • setSelectionRange() reference

  • attribute

    • selectionStart
      The position index of the first character selected, starting from 0. If this value is larger than the value length of the element, it will be regarded as the index of the last position of value.
    • selectionEnd
      The next position index of the last character selected. If this value is larger than the value length of the element, it will be regarded as the index of the last position of value.
    • selectionDirection optional
      A string representing the selection direction. The possible values are: "forward", "backward" and "none". The default value indicates that the direction is unknown or irrelevant.

Introduction to Selection

  • Selection MDN

  • concept
    The Selection object represents the current position of the text range or caret selected by the user. It represents the text Selection in the page and may span multiple elements.
    The text Selection is generated by the user dragging the mouse through the text. To get the Selection object for checking or modifying, call window getSelection().
    A Selection object represents a collection of ranges selected by the user. Usually, it contains only one area

    var selObj = window.getSelection();
    var range  = selObj.getRangeAt(0);
    
  • selectionchange event

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div>
      Enter and select text here:<br /><input id="mytext" rows="2" cols="20" />
    </div>
    <div>selectionStart: <span id="start"></span></div>
    <div>selectionEnd: <span id="end"></span></div>
    <div>selectionDirection: <span id="direction"></span></div>
  </body>
  <script>
    const myinput = document.getElementById("mytext");
    // myinput. Addeventlistener ("selectionchange", () = > {this is invalid
    document.addEventListener("selectionchange", () => {
      // Only HTMLInputElement nodes have selectionStart selectionEnd selectionDirection property
      document.getElementById("start").textContent = myinput.selectionStart;
      document.getElementById("end").textContent = myinput.selectionEnd;
      document.getElementById("direction").textContent =
        myinput.selectionDirection;
    });
  </script>
</html>

Range

  • Range MDN

  • concept
    The Range interface represents a document fragment containing a part of a node and a text node.
    Scope refers to a continuous part of a document. A range includes the entire node or part of the node, such as part of a text node. Usually, users can only select one range, but sometimes users may also select multiple ranges.
    You can use the Document of the Document object The createrange method creates a Range, or you can use the getRangeAt method of the Selection object to get the Range. In addition, you can also get the Range through the constructor Range() of the Document object.

5, Code set

Adds a string at the cursor position of the text control

<html>
  <head> </head>
  <script type="text/javascript">
    function add(str) {
      var tc = document.getElementById("mytextarea");
      var tclen = tc.value.length;
      tc.focus();
      if (typeof document.selection != "undefined") {
        document.selection.createRange().text = str;
      } else {
        tc.value =
          // Gets the start position of the cursor
          tc.value.substr(0, tc.selectionStart) +
          str +
          tc.value.substring(tc.selectionStart, tclen);
      }
    }

    function selectAll() {
      var tc = document.getElementById("mytextarea");
      // Select all textarea contents
      tc.select();
      // Focus selection
      tc.focus();
    }

    function selectPos() {
      var start = 5,
        end = 10;
      var tc = document.getElementById("mytextarea");
      // If it is not selected, it starts from 0 by default
      console.log(tc.selectionStart);
      // If no area is selected, it is in the same position as selectionStart
      console.log(tc.selectionEnd);
      // Set the selected area, and the selected content will not be highlighted in the browser
      tc.setSelectionRange(start, end);
      // Selected start position
      console.log(tc.selectionStart);
      // Selected end position
      console.log(tc.selectionEnd);
      var str = "huangbiao";
      var tclen = tc.value.length;
      tc.value =
        tc.value.substr(0, tc.selectionStart) +
        str +
        tc.value.substring(tc.selectionStart, tclen);
    }

    function getSelectObj() {
      // Get the object selected on the user page
      var selObj = window.getSelection();
      // Call selection The toString () method returns plain text in the selected area.
      window.alert(selObj);
    }

    function getRangeObj() {
      var selObj = window.getSelection();
      // Get Range object
      var range = selObj.getRangeAt(0);
      console.log(range);
    }
  </script>
  <body>
    <textarea rows="5" name="s1" cols="27" id="mytextarea">
Purpose by clicking the button on the page button stay textarea Insert text where the cursor stays in the </textarea
    >

    <ul>
      <li>
        <button onclick="selectAll()">
          select all 
        </button>
      </li>
      <li>
        <button onclick="add('huangbiao')">Add specified string</button>
      </li>
      <li>
        <button onclick="selectPos()">
          Customize the selected location
        </button>
      </li>
      <li>
        <button onclick="getSelectObj()">
          Gets the selected value
        </button>
      </li>
      <li>
        <button onclick="getRangeObj()">
          Get selected Range object
        </button>
      </li>
    </ul>
  </body>
</html>

Topics: Front-end