We often encounter some problems, that is, to move the cursor in the textbox to the text currently entered. Next I will introduce you to the summary of how to move the cursor to the text currently entered.
When I write a winform application today, I want to write a text box similar to the amount input by the bank, that is, when the user enters the full number of digits, an identifier such as a comma is automatically added to the end, character judgment is well implemented in TextChanged, but the problem is that when I judge that the input is full 8 digits, a comma is automatically added, however, the cursor of the text box will run to the starting position of the text box, which is inconvenient. So I found some solutions. The Code is as follows:
| The Code is as follows: |
Copy code |
Private void textBox9_TextChanged_1 (object sender, EventArgs e) { If (textBox9.Text. Length = 8 * (I + 1) + I) { TextBox9.Text + = ","; I ++; TextBox9.SelectionStart = int. MaxValue; } } |
You can use the selectionstart attribute of textbox to set the cursor position.
Js Code
GetCursortPosition and setCursorPosition functions in mainstream browsers such as IE, Firefox, and Opera.
| The Code is as follows: |
Copy code |
Function getCursortPosition (ctrl) {// obtain the cursor position function Var CaretPos = 0; // IE Support If (document. selection ){ Ctrl. focus (); Var Sel = document. selection. createRange (); Sel. moveStart ('character ',-ctrl. value. length ); CaretPos = Sel. text. length; } // Firefox support Else if (ctrl. selectionStart | ctrl. selectionStart = '0 ') CaretPos = ctrl. selectionStart; Return (CaretPos ); } |
PS: ctrl is the input or textarea object.
| The Code is as follows: |
Copy code |
Function setCaretPosition (ctrl, pos) {// set the cursor position function If (ctrl. setSelectionRange) { Ctrl. focus (); Ctrl. setSelectionRange (pos, pos ); } Else if (ctrl. createTextRange ){ Var range = ctrl. createTextRange (); Range. collapse (true ); Range. moveEnd ('character ', pos ); Range. moveStart ('character ', pos ); Range. select (); } } |
PS: ctrl is the input or textarea object, and pos is the position to move the cursor