cursor is jumping when pressing the arrow keys

前端 未结 5 933
日久生厌
日久生厌 2021-01-07 14:26

I have a textbox, where a forbidden character cant be typed. #.

This works, however, when the textbox is filled in with data, and I put the focus on the middle of th

5条回答
  •  借酒劲吻你
    2021-01-07 15:02

    Javascript allows you to set the cursor position for inputs.

    I found two useful functions:

    • getCaretPosition - https://stackoverflow.com/a/2897229/2335291
    • setCaretPosition - https://stackoverflow.com/a/512542/2335291

    And the solution could look like this:

      function getCaretPosition (elem) {
    
        // Initialize
        var iCaretPos = 0;
    
        // IE Support
        if (document.selection) {
    
          // Set focus on the element
          elem.focus ();
    
          // To get cursor position, get empty selection range
          var oSel = document.selection.createRange ();
    
          // Move selection start to 0 position
          oSel.moveStart ('character', -elem.value.length);
    
          // The caret position is selection length
          iCaretPos = oSel.text.length;
        }
        // Firefox support
        else if (elem.selectionStart || elem.selectionStart == '0')
          iCaretPos = elem.selectionStart;
    
        // Return results
        return (iCaretPos);
      }
    
      function setCaretPosition(elem, caretPos) {
          if(elem != null) {
              if(elem.createTextRange) {
                  var range = elem.createTextRange();
                  range.move('character', caretPos);
                  range.select();
              }
              else {
                  if(elem.selectionStart) {
                      elem.focus();
                      elem.setSelectionRange(caretPos, caretPos);
                  }
                  else
                      elem.focus();
              }
          }
      }
    
    $('[id$=txtClient]').keyup(function () {
        EnableClientValidateButton(); // When the textbox changes, the user has the ability to validate the client
        ChangeColorClient("0"); // The color is changed to white, to notify the user the client is not validated yet.
        var $el = $('[id$=txtClient]'); // the text element to seach for forbidden characters.
        var text = $el.val(); // The value of the textbox
        text = text.split("#").join("");//remove occurances of forbidden characters, in this case #
    
        var pos = getCaretPosition(this);
        $el.val(text);//set it back on the element
        setCaretPosition(this, pos);
    });
    

提交回复
热议问题