Search code examples
jqueryasp.netmaskedinput

ASP.NET, TextBoxFor using JQuery MaskedInput not accepting input when others do


I have a @Html.TextBoxFor(...) not accepting any input when I assign it a .mask("(999) 999-999"); in a supporting JavaScript file, why?

The textbox in question is located in MainFocus.cshtml with this HTML:

<div id="telephoneNumber" class="col-sm-3" style="width: 22% !important;">
    <div>
        <label class="required">Telephone:</label>
    </div>
    <div>
        @Html.TextBoxFor(m => m.Telephone, new { id = "telephoneNumber", placeholder = "(xxx) xxx-xxxx", maxlength = "14" })
        @Html.ValidationMessageFor(m => m.Telephone)
    </div>
    [...]
</div>

I then apply the mask in this Javascript file, supportingScript.js:

$("#telephoneNumber").mask("(999) 999-9999");

When I run the site, the masked textbox does not accept any input at all, despite the fact that other textboxes on the page that have also been masked the same way in supportingScript.js work just fine.

Why is this?


Solution

  • The problem here is that the div tag has the same id value as the textbox:

    <div id="telephoneNumber" ...>
    
    @Html.TextBoxFor(m => m.Telephone, new { id = "telephoneNumber", ... })
    

    Simply remove the id from the div tag or change it to a value not used elsewhere in the .cshtml, and your textbox should now be masked properly.