简体   繁体   中英

Javascript disabling my postback

I have an ASP.NET checkbox, and I want to run some javascript before it posts back.

Something like:

<asp:CheckBox ID="chkSelected" runat="server" AutoPostBack="True" OnCheckedChanged="chkSelected_CheckedChanged" />

but I want to run a JS confirm dialog when the user click it, and if they were UNCHECKING it, I'd like to ask them if they're sure, and if so, postback and run my serverside code. If they say No, don't postback at all.

Anyone know of an 'easy' way to do this?

You can add an onclick handler:

<asp:CheckBox ... onclick="if (!this.checked && !confirm('Are you sure?')) return false;" />

(I believe this will work, but I didn't try it)

You can also add an event in Javascript. (which is more likely to work)
Using jQuery:

$('#<%=chkSelected.ClientID%>').click(function() {
    return this.checked || confirm('Are you sure?');
});

I haven't tried this with a checkbox but try to see if there is an OnClientClick attribute for your asp:CheckBox. If there is, put the name of the javascript function in it. Then in your javascript you can return true if the postback should happen or return false if you want to cancel the postback.

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