David
David

Reputation: 81

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 more than 13 characters.

Upvotes: 4

Views: 3434

Answers (3)

zachelrath
zachelrath

Reputation: 852

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>

Upvotes: 0

jfriend00
jfriend00

Reputation: 707158

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.

Upvotes: 1

Stefano
Stefano

Reputation: 4031

somethink like this may work:

<html>
<body>


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

</body>
</html>

Upvotes: 0

Related Questions