Set cursor position while focus on the input textbox

21 Dec 20221 minute to read

By default, on focusing the MaskedTextBox the entire mask gets selected. You can customize by using any one of the following methods:

  • Setting cursor position at the start of the MaskedTextBox.
  • Setting cursor position at the end of the MaskedTextBox.
  • Setting cursor at the specified position in the MaskedTextBox.

NOTE

The selectionStart and selectionEnd set to 0 instead of the input element value’s length, when we focus on a MaskedTextBox control filled with all mask characters. This is the default behavior of the HTML 5 input element.

Following is an example that demonstrates the above cases to set cursor position in the MaskedTextBox using focus event.

@Html.EJS().MaskedTextBox("mask1").Mask("00000-00000").Value("93828-32132").Placeholder("Default cursor position").FloatLabelType(Syncfusion.EJ2.Inputs.FloatLabelType.Always).Render()
@Html.EJS().MaskedTextBox("mask2").Mask("00000-00000").Value("83929-4342").Placeholder("Cursor positioned at start").FloatLabelType(Syncfusion.EJ2.Inputs.FloatLabelType.Always).Focus("onfocus").Render()
@Html.EJS().MaskedTextBox("mask3").Mask("00000-00000").Value("83929-3213").Placeholder("Cursor positioned at end").FloatLabelType(Syncfusion.EJ2.Inputs.FloatLabelType.Always).Focus("onfocus1").Render()
@Html.EJS().MaskedTextBox("mask4").Mask("+1 000-000-0000").Value("234-432-432").Placeholder("Cursor at specified position").FloatLabelType(Syncfusion.EJ2.Inputs.FloatLabelType.Always).Focus("onfocus2").Render()


<script>

    function onfocus(args) {
        //sets cursor position at start of MaskedTextBox
        args.selectionEnd = args.selectionStart = 0;
    }

    function onfocus1(args) {
        //sets cursor position at end of MaskedTextBox
        args.selectionStart = args.selectionEnd = args.maskedValue.length;
    }

    function onfocus2(args) {
        //sets cursor at specified position
        args.selectionStart = 3;
        args.selectionEnd = 3;
    }

</script>
public ActionResult cursorPosition()
{
    return View();
}

Output be like the below.

MaskedTextBox Sample