Search code examples
c#asp.net-coremodel-view-controllerrazor

ASP.NET Core MVC Jump to next textbox after x digits


I have 3 text fields in an ASP.NET Core MVC website. These text fields can have a maximum of 4 characters per field and should jump to the next textbox after the fourth character entered.

I have the following code, but it does not work. After entering the fourth digit the cursor stays in the textbox.

<script type="text/javascript">
    $(document).ready(function jumpToNextTextbox(event, nextTextboxId) {
        if (event && event.target.value.length === event.target.maxLength) {
            document.getElementById(nextTextboxId).focus();
        }
    })
    });
</script>

I have inserted an alert before and in the if-query for testing, but it is not output.

The text boxes look like this:

<div class="col-sm-2" style="margin-right:2px;">
    @Html.TextBoxFor(model => model.Field1, new { oninput = "limitInput(this, 4); jumpToNextTextbox(event, 'field2')", @class = "form-control", maxlength = "4", htmlAttributes = new { id = "field1" } })
</div>

<div class="col-sm-2" style="margin-right:2px;">
    @Html.TextBoxFor(model => model.Field2, new { oninput = "limitInput(this, 4); jumpToNextTextbox(event, 'field3')", @class = "form-control", maxlength = "4", htmlAttributes = new { id = "field2" } })
</div>
                    
<div class="col-sm-2" style="margin-right:2px;">
    @Html.TextBoxFor(model => model.Field3, new { oninput = "limitInput(this, 4); jumpToNextTextbox(event, 'field1')", @class = "form-control", maxlength = "4", htmlAttributes = new { id = "field3" } })               
</div>

At which point is something still missing?


Solution

  • You can try this working demo:

    <div class="col-sm-2" style="margin-right:2px;" >
        <input class="inputs" asp-for="Field1" maxlength="4" />
        <input class="inputs" asp-for="Field2" maxlength="4" />
        <input class="inputs" asp-for="Field3" maxlength="4" />
    </div>  
    
    @section Scripts{
        <script>
            $(".inputs").keyup(function () {
                if (this.value.length == this.maxLength) {
                    var $next = $(this).next('.inputs');
                    if ($next.length)
                        $(this).next('.inputs').focus();
                    else
                        $(this).blur();
                }
            });
        </script>
    }
    

    Gif Demo

    enter image description here

    Refer to this link.