Phone Mask in ASP.Net

2019-09-16 13:55发布

问题:

i am doing a ASP.Net application and I need to use phone mask input in a TextBox. I am using jQuery and it is not working.

Asp.net:

<asp:TextBox runat="server" ID="txtCelular" CssClass="w240 placeholder"></asp:TextBox>

javascript:

    <script src="\scripts\jquery-1.7.2.js" type="text/javascript"></script>
<script type="text/javascript">
    $("#txtCelular").mask("(999) 9999-9999?9");


    $("#txtCelular").on("blur", function () {
        var last = $(this).val().substr($(this).val().indexOf("-") + 1);

        if (last.length == 5) {
            var move = $(this).val().substr($(this).val().indexOf("-") + 1, 1);

            var lastfour = last.substr(1, 4);

            var first = $(this).val().substr(0, 9);

            $(this).val(first + move + '-' + lastfour);
        }
    });
</script>

回答1:

You have to keep in mind that the ID you specify on elements on the server, by default, is not the ID that is used on the client. And since JavaScript runs on the client, then it's not getting the right element because of the ID mismatch. You have a number of options. This often trips up new Web Forms developers when they start using Master Pages, templated controls, or user controls (.ascx).


Change Client Id Mode approach

You can change ClientIdMode for the element (this can also be done at the page or web.config levels).

<asp:TextBox runat="server" ID="txtCelular" ClientIdMode="static" CssClass="w240 placeholder" />

Embed Client ID approach

You can embed the Client ID in the JavaScript, as long as your JavaScript is directly in a Web Forms page or control.

$("#<%= txtCelular.ClientId %>").mask("(999) 9999-9999?9");

Use a class approach

Or in some situations (this is a good candidate), a class makes more sense.

<asp:TextBox runat="server" ID="txtCelular" CssClass="w240 placeholder phonemask" />

$(".phonemask").mask("(999) 9999-9999?9");