Onkeyup char position in line

How to find the position of a character entered in a string when a key is pressed using JavaScript? I am trying to create an input mask and the user is not allowed to enter more than 13 characters.

+4
source share
3 answers

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

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

Also, looking at selectionEnd , you can see if one or more characters are selected, and not just a simple insertion point.

+1
source

something like this might work:

 <html> <body> <form> <input type="text" name='element1' maxlength="13" /> </form> </body> </html> 
0
source

Try using this code in your browser - should provide you with 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
source

All Articles