How To Work maxlength For Input Type Number

How To Work maxlength For Input Type Number


I have a View that has a TextBoxFor ( type="number" ). I am trying to limit my TextBoxFor to include max 11 characters.


Maximum length works with <input type = "text", but maximum length doesn't work with <input type = "number".


So I need to use jQuery.


<div class="col-12 col-md-6">
    <div class="form-group">

        @Html.LabelFor(m => m.personID)
        @Html.TextBoxFor(m => m.personID, new { @class = "form-control", placeholder = "Enter Person ID", type = "number", maxlength = "11", autocomplete = "off" })
        @Html.ValidationMessageFor(m => m.personID, null, new { @class = "text-danger" })

    </div>
</div>

The maxlength attribute specifies the maximum number of characters allowed in the <input> element.


The best way is to use keyup event to limit the maximum length.


<script type="text/javascript">
    $(document).ready(function () {
        $("#personID").keyup(function () {
            if ($(this).val().length > $(this).attr("maxlength")) $(this).val($(this).val().slice(0, $(this).attr("maxlength")));
        });  
    });
</script>

This code above work for me.


maxlength.PNG

tag : asp.net TextBoxFor char limit,input length limit jquery,type=number maxlength