jQuery Interrupt ASP.net server placed <submit />
I've got some really odd behavior I basically want a pretty styling to my buttons and I want a modal confirmation form on saving and discarding changes to a web form. The events that do the saving and discarding are asp.net events tied to server controls, by decorating the buttons with a class I can get jQuery to make them look pretty and clicking on them works as if they were bog standard server side controls.
So I wrote a little script that basically goes:
$("#confirmSave-dialog").dialog({
resizable: false,
autoOpen: false,
height: 150,
modal: true,
buttons: { 'Save': function() {
$(".SAVER").trigger('click');
$(this).dialog('close');
},
'Cancel': function() {
$(this).dialog('close');
}
}
});
$(".SAVER").button();
$(".SAVER").click(function(event) {
var bool = $("#confirmSave-dialog").dialog('isOpen');
if (!bool) {
event.preventDefault();
$("#confirmSave-dialog").dialog('open');
}
});
The idea being that when the user clicks the button it brings up a control and interrupts the click event causing a postback but if they click save on the form then the click event sees the form is open and should not interrupt the postback. The issue is that it seems random if this works. It wasn't working and I moved it to a separate function and whacked in some debugger directives like so:
$(".SAVER").click(function(event) {
var bool = $("#confirmSave-dialog").dialog('isOpen');
if (!bool) {
debugger;
event.preventDefault();
$("#confirmSave-dialog").dialog('open');
}
debugger;
});
With Firebug running every now and then it fires the event 开发者_StackOverflow中文版as it should, with Firebug not running it never does, without the debugger directives it never does.
Even with the debugger running it follows the right path the first time the event is triggered by the click it goes and kicks up the dialog and then when save is clicked it skips out the event.preventDefault();
call but doesn't fire the postback.
No idea why; any ideas/ways to fix/ better ways of firing the serverside event?
Try controlling the postback manually in your JS function. So clicking the button always interupts the postback. Works for me everytime.
So on the button:
<asp:LinkButton ID="btnMyButton" runat="server" class="button" Text="Save Form" OnClientClick="return mySubmit();return false;" />
Then create a mySubmit JS Function:
<script type="text/javascript">
function mySubmit() {
if (!Foo == Bar ) {
//return false to cancel the page postback or form submit
return false;
} else {
// manually call the postback (Asp.net only)
__doPostBack('<%= btnMyButton.UniqueID%>', '')
// return true to submit the page.
return true;
}
}
精彩评论