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 开发者_StackOverflow中文版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.
精彩评论