Trigger jQuery code on AutoPostBack = true?

巧了我就是萌 提交于 2019-12-12 10:03:33

问题


I have a bit of jQuery code that applies a phone number mask to a text field in a form:

<script type="text/javascript" src="../../../js/jquery.maskedinput.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $.mask.definitions['~'] = '[+-]';
        $('.phone').mask('(999) 999-9999');
    });
</script>

It works just fine when the user first enters the form or if the use refreshes the page. However, there is a DropDownList that will allow users to select a different shipping address. This DropDownList has its AutoPostBack Property set to "true."

   <tr id="trAddressBook" runat="server">
        <th>Ship To:</th>
             <td>
                <asp:DropDownList ID="AddressBook" runat="server" Width="200px" DataTextField="Value" DataValueField="Key" AppendDataBoundItems="true" AutoPostBack="true">
                     <asp:ListItem Text="Billing Address" Value="0" />
                      <asp:ListItem Text="New Address" Value="-1" />
                 </asp:DropDownList>
              </td>
 </tr>

Whenever the user select an option from this DropDownList, the phone mask jQuery code no longer appears in the phone number textbox(es). I don't see any errors when I inspect the page in Google Chrome.

Is there someway to maintain the phone mask code regardless of whether the user uses the DropDownList or not?

Here is the Page_Load function from the code behind:

    protected void Page_Load(object sender, EventArgs e)
    {
        // DETERMINE IF THE SHIPPING FORM MUST BE INITIALIZED
        bool initShipAddress;
        if (Page.IsPostBack)
        {
            // ON POSTBACK, WE ONLY INITIALIZE THE SHIPPING FORM IF THE ADDRESS SELECTION WAS CHANGED
            initShipAddress = (Request.Form["__EVENTTARGET"] == AddressBook.UniqueID);         
        }
        else
        {
            // ON FIRST VISIT, WE INITIALIZE SHIPPING FORM IF THE SHIPPING ADDRESS IS NOT THE BILLING
            initShipAddress = (GetShippingAddressId() != _User.PrimaryAddress.Id);
        }
        if (initShipAddress) InitializeShippingAddress();
    }

回答1:


I may be wrong as it's been a long time since I worked with ASP.NET, but I believe you can simply change $(document).ready(function () { ... }); to $(window).load(function() { ... });

$(window).load(function () {
    $.mask.definitions['~'] = '[+-]';
    $('.phone').mask('(999) 999-9999');
});

Failing that, ASP.NET executes a function called pageLoad every time a page loads:

function pageLoad() {
    $.mask.definitions['~'] = '[+-]';
    $('.phone').mask('(999) 999-9999');
};


来源:https://stackoverflow.com/questions/22510926/trigger-jquery-code-on-autopostback-true

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