简体   繁体   中英

Ensure TextBox OnTextChanged (ASP.NET injects a “setTimeout”) fires before OnClick

Consider the following scenario:

<asp:TextBox ID="txt" runat="server" AutoPostBack="true" OnTextChanged="txt_TextChanged"></asp:TextBox>
<asp:Button ID="btn" runat="server" OnClick="btn_Click" CausesValidation="false" UseSubmitBehavior="false" />

when rendered, those two controls become:

<input name="txt" type="text" onchange="javascript:setTimeout('__doPostBack(\'txt\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="txt">
<input type="button" name="btn" onclick="javascript:__doPostBack('btn','')" id="btn">

thanks to the setTimeout, the Click event is firing before the Change event.

After some research , I discovered that ASP.NET does this because of an old glitch in some older versions of IE.

However, this is causing problems because my button click hides the textbox, causing some "Invalid postback or callback" errors.

How can I fix the execution order, so the TextChanged always fires before Click?

PS : I am willing to use Javascript/jQuery to change one of the events, but I'm in doubt about the performance of such solutions (since I would probably be forced to use eval for it)

I solved it using a bit of a hack, I'm still open for a better solution if anyone knows one.
For now, I'm calling this function on the page load:

function removeSetTimeout() {
    var inputs = "select, input[type=text], input[type=number], input[type=date], input[type=time]";
    $(inputs).each(function (index, elem) {
        var change = $(elem).attr('onchange');
        if (change) {
            var patch = /setTimeout\('__doPostBack\(\\'.*?\\',\\'\\'\)', 0\)/.exec(change);
            if (patch) {
                change = change.replace(patch[0], patch[0].substring(12, patch[0].length - 5).replace(/\\/g, ''));
                $(elem).attr('onchange', change);
            }
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM