Phone Mask in ASP.Net

落爺英雄遲暮 提交于 2019-12-12 03:18:41

问题


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");


来源:https://stackoverflow.com/questions/32096370/phone-mask-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!