开发者

onkeyup char position in string

How does one find the position of the character being entered into the string on keypress using JavaScript? I am trying to build an input mask and the user should not be allowed to input mor开发者_开发知识库e than 13 characters.


I think the answer to your direct question is that the selectionStart attribute of the input field will tell you where the insertion cursor is.

function myKeypress() {
    console.log(this.selectionStart);  // tells you where the insertion cursor is
}

By also looking at selectionEnd you can see if one or more characters are selected too rather than just a plain insertion point.


somethink like this may work:

<html>
<body>


<form>
<input type="text" name='element1' maxlength="13" />
</form>

</body>
</html>


Try this code in your browser --- should give you the tools to accomplish your task.

<html>
<body>
<script type="text/javascript">

function getTextAreaSelection() {
  var textArea = document.getElementById('textarea1');
  if (document.selection) { //IE
      var bm = document.selection.createRange().getBookmark();
      var sel = textArea.createTextRange();
      sel.moveToBookmark(bm);

      var sleft = textArea.createTextRange();
      sleft.collapse(true);
      sleft.setEndPoint("EndToStart", sel);
      textArea.selectionStart = sleft.text.length
      textArea.selectionEnd = sleft.text.length + sel.text.length;
      textArea.selectedText = sel.text;
  }
  else if (textArea.selectionStart){ //FF
     textArea.selectedText = textArea.value.substring(textArea.selectionStart,textArea.selectionEnd);
  }

  alert("Selection Start==> " + textArea.selectionStart + "\n" +
     "Selection End  ==> " + textArea.selectionEnd + "\n" +
     "Selected Text  ==> " + textArea.selectedText + "\n" +
     "TextArea Value ==> " + textArea.value);
}

</script>

<form>
    <textarea id="textarea1">Hello world</textarea>
    <input type="button" onClick="getTextAreaSelection();return false;" value="Get Selection"/>
</form>
</body>
</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜