I am using jquery onbeforeunload event in asp.net application.
If i write event as given below then its working fine and display confirm dialog box.
var vGlobal = true;
var sMessage = "Leaving the page will lost in unsaved data!";
[ Working ]
> window.onbeforeunload = function() {
> if (vGlobal == false) return
> sMessage; }
but its not working if i use bind method like as given below
[ Not working ]
$(window).bind("beforeunload", function(e) {
if (vGlobal == false)
return sMessage;
});
Anybody suggest me why its not working.Is there any difference between these two methods.
Code on aspx:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
CLICK ON THIS LINK TO SEE RUNNING EXAMPLE
See the updated version
You need to bind all the events inside document ready event.
Apart from the fact that vGlobal is true and you are checking if (vGlobal == false), this smells like a $(document).ready() issue.
I.e. you should place the declaration inside a document.ready() handler as shown here:
$(document).ready(function(){
$(window).bind("beforeunload", function(e) {
if (vGlobal == false)
return sMessage;
});
});
There is no benefit in using jQuery to bind the event to the window - all you are doing is adding the overhead of having jQuery parse the window into a jQuery object, which you aren't even using.
Therefore, using:
window.onbeforeunload = handler;
Is preferable to using jQuery to bind this event.
You can still perform the binding inside of the document ready section:
$(document).ready(function () {
window.onbeforeunload = handler;
};
Related
I'm trying to use a simple jquery-ui modal dialog as a delete confirmation in an ASP.NET C# application. I've done this many times before, but for some reason in this application it is misbehaving. I see the dialog pop up then it immediately disappears before I can click on either "Yes" or "No". Here's the relevant code (Javascript):
<script type="text/javascript" src="/resources/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="/resources/jquery-ui-1.9.1.custom.min.js"></script>
<link rel="stylesheet" type="text/css" href="/resources/ui-lightness/jquery-ui-1.9.1.custom.css" />
<script type="text/javascript">
var remConfirmed = false;
function ConfirmRemoveDialog(obj, title, dialogText) {
if (!remConfirmed) {
//add the dialog div to the page
$('body').append(String.Format("<div id='confirmRemoveDialog' title='{0}'><p>{1}</p></div>", title, dialogText));
//create the dialog
$('#confirmRemoveDialog').dialog({
modal: true,
resizable: false,
draggable: false,
close: function(event, ui) {
$('body').find('#confirmRemoveDialog').remove();
},
buttons:
{
'Yes, remove it': function() {
$(this).dialog('close');
remConfirmed = true;
if (obj) obj.click();
},
'No, keep it': function() {
$(this).dialog('close');
}
}
});
}
return remConfirmed;
}
//String.Format function (since Javascript doesn't have one built-in
String.Format = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, arguments[i + 1]);
}
return s;
}
</script>
Here's where I'm using the confirmation function (in the OnClientClick of an <asp:Button> control):
<asp:Button ID="btnRemoveProgram" runat="server" Text="Remove" CausesValidation="false" OnClientClick="ConfirmRemoveDialog(this, 'Please confirm removal', 'Are you sure you wish to remove the selected Program? This cannot be undone.');" />
As I said, I've successfully used this same construct (nearly identical code) many times before; I don't know why it isn't working now. Any ideas will be greatly appreciated, I'm truly stumped on this one.
The runat="server" is telling the button that it should post back to perform events at the server. The OnClientClick will be executed before that on the client side, so you will see the dialog and then immediate the page posts, causing the dialog to disappear.
The problem is that your modal dialog box is not modal in the traditional windows sense. The javascript continues on. The simplest test is to add an alert right before your return, you will see it pops up right after the dialog is shown.
To get around this issue, return false always in the OnContentClick and then in your Yes/No button event handlers use the __doPostback javascript method.
You need to return the remConfirmed to the caller which is the button itself. On your button, do this:
OnClientClick="return ConfirmRemoveDialog(/* the rest of the code */);"
I need to get the id of the panel that is about to start a postback, so I have a generic way to block ui on this panel.
So far I have this function:
function BeginRequestHandler(sender, args) {
$('#' + args.get_updatePanelsToUpdate()[0]).block({ message: null });
}
attached like this:
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
this works pretty well to get the id if control that causes partial postback is inside update panel, but if it is outside (using a trigger), args.get_updatePanelsToUpdate() is always null
I've seen this answer, but it wont work forme because function is fired after partial postback is complete, I need it before..
Thank you
So here's what I did:
created 2 functions to block (on partial postback begin) and unblock (on partial postback end):
function BeginRequestHandler(sender, args) {
$('#' +sender._postBackSettings.panelsToUpdate[0].ReplaceAll('$', '_')).block({ message: 'loading...' });
}
function EndRequestHandler(sender, args) {
$('#' + sender._postBackSettings.panelsToUpdate[0].ReplaceAll('$', '_')).unblock();
}
Registered above functions on my page right after my script manager:
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
</script>
Some conditions:
I'm using jquery UI block plugin but you should use what better fits your needs.
You update panels should have ClientIDMode="AutoID" if your using .NET 4.0 +
I used the following helper function cause js doesn't make a real replace all and to deal with asp net autoID's:
String.prototype.ReplaceAll = function (stringToFind, stringToReplace) {
var temp = this;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
}
If you just want to disable (or animate in some other way) the UpdatePanel, why not just use UpdatePanelAnimation? It provides you with the following hooks (not sure if that's the right word):
OnUpdating - Generic animation played as when any UpdatePanel begins
updating
OnUpdated - Generic animation played after the UpdatePanel
has finished updating (but only if the UpdatePanel was changed)
I have a C# ASP.NET web page with an xml file upload form. When the user clicks 'upload', a javascript confirm alert will pop up asking the user, "is this file correct?". The confirm alert will only activate if the file name does not contain a value from one of the other form fields.
What is the best way to combine the use of a C# ASP.NET form and a javascript confirm alert that is activated if the name of a file being uploaded does not meet certain criteria?
There's not much you need to do with C# for this page, it sounds like most of this will be done on the client side.
Add the fileupload control and a button to your .aspx form. Set the Button's OnClientClick property to something like
OnClientClick = "return myFunction()"
and then write a javascript function like:
function myFunction()
{
// Check other text values here
if (needToConfirm){
return confirm('Are you sure you want to upload?');
}
else return true;
}
Make sure "myFunction()" returns false if you wish to cancel the postback (i.e. the user clicked "no" in the confirm dialog). This will cancel the postback if they click "No".
I suppose you are putting value of valid string in a hidden field (you haven't mentioned). Implement OnClientClick for Upload button:
<asp:button .... OnClientClick="return confirmFileName();"/>
<script type="text/javascript">
function confirmFileName()
{
var f = $("#<%= file1.ClientID %>").val();
var s=$("#<%= hidden1.ClientID %>").attr("value");
if (f.indexOf(s) == -1) {
if (!confirm("Is this correct file?")) {
$("#<%=file1.ClientID %>").focus();
return false;
}
}
return true;
}
</script>
EDIT:- Regarding <%= file1.ClientID %>.
This will be replaced by the client side ID of the file upload control like ctl00$ctl00$cphContentPanel$file1. It puts the script on steroids with respect to using something like $("input[id$='file1']"). For more information please see Dave Wards' post.
window.onload = function() {
document.forms[0].onsubmit = function() {
var el = document.getElementById("FileUpload1");
var fileName = el.value;
if(fileName.indexOf("WHATEVER_VALUE") == -1) {
if(!confirm("Is the file correct?")) {
el.focus();
return false;
}
}
return true;
}
}
I had problems implementing this kind of thing to work in both IE and FireFox because of the way events work in those browsers. When I got it to work in one of them, the other would still cause a postback even if I cancelled out.
Here's what we have in our code (the browser test was stolen from elsewhere).
if (!window.confirm("Are you sure?"))
{
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
window.event.returnValue = false;
else
e.preventDefault();
}
In addition to using client side validation, you should also add a CustomValidator to provide validation on the server side. You cannot trust that the user has Javascript turned on, or that the user has not bypassed your Javascript checks.
I have an ASP.NET page with a number of ASP:Button instances on it. For some, I need to show a confirmation prompt and, should the user choose yes, the original postback method is called. Otherwise, the overall process is cancelled.
I've got an example running but I get inconsistent results, mainly in FF3 where I get an exception thrown:
[Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "JS frame ::
I've looked this error up but I'm drawing a loss as to where I'm going wrong. Here's my example case. Note, for now I'm just using the css class as a lookup. Longer term I can embed the clientID of the control into my JS if it proves necessary :).
Html fragment:
<asp:Button ID="StartButton" runat="server" CssClass="startbutton" Text="Start" OnClick="OnStartClicked" />
Javascript:
$(".startbutton").each(function(){
$(document).data("startclick", $(this).get()[0].click);
$(this).unbind("click");
}).click(function(){
var oldclick = $(document).data("startclick");
alert("hello");
try
{
oldclick();
}
catch(err)
{
alert(err);
alert(err.description);
}
return false;
});
My code behind is relatively simple, the OnStart method simply executes a Response.Write
I've only just started looking into bind, unbind and trigger so my usage here is pretty much 'first time'.
Thanks for any help or advice.
S
EDIT:
This describes what I'm trying to do and also gives a run down of the kind of pitfalls:
http://www.nabble.com/onClick-prepend-td15194791s27240.html
How about this?
$(document).ready( function() {
$('.startbutton').click(function() {
return confirm('Are you sure?');
})
});
I've solved my problem for IE7 and FF3.
The trick is to make the postback work as an 'onclick' via an ASP.NET attribute on the button (see below). In Javascript this gets pulled out as a function reference when you read the click in JQuery.
To make it work, you then clear the onclick attribute (after saving it) and call it later on.
My code below shows it in action. This code isn't complete as I'm part way through making this into a generic prompt for my application. Its also a bit badly laid out! But at least it shows the principle.
ASP.NET button
<asp:Button ID="StartButton" runat="server" CssClass="startbutton" Text="Start" OnClick="OnStart" UseSubmitBehavior="false" />
Javascript:
$(".startbutton").each(function(){
$(document).data("startclick", $(this).attr("onclick"));
$(this).removeAttr("onclick");
}).click(function(){
$.blockUI({ message: $('#confirm'), css: { width: '383', cursor: 'auto' } });
$("#yes").click(function(){
$.unblockUI();
var oldclick = $(document).data("startclick");
try
{
oldclick();
}
catch(err)
{
alert(err);
alert(err.description);
}
});
$("#no").click(function(){
$.unblockUI();
});
return false;
});
Your problem comes from here :
$(document).data("startclick", $(this).get()[0].click);
...
var oldclick = $(document).data("startclick");
...
oldclick();
Here, you try to intercept a native event listener but there are two errors :
Using unbind will not remove the native event listener, just the ones added with jQuery
click is, AFAIK, a IE only method used to simulate a click, it not the event handler itself
You'll have to use onclick instead set its value to null instead of using unbind. Finally, don't store it in $(document).data(...), you'll have some problems when you add other buttons. Here is a sample code you can use :
$("selector").each(function()
{
var oldclick = this.onclick;
this.onclick = null;
$(this).click(function()
{
if (confirm("yes or no ?")) oldclick();
});
});
for mi works:
this.OnClientClick = "$.blockUI({ message: $('#ConfirmacionBOX'), css: { width: '275px' } });return false;";
This is a button (is a button class)
Short Explanation:
I have a script control that has the click event being handled in the script file. The Click handler pops up a confirm prompt and returns the prompt's value.
Problem:
IE sees the return False (Cancel is selected on the confirm box) and there is no postback. Firefox ignores this and fires the postback.
Solution?:
I read that if I were doing this the old fashion way, I would need to have:
onClick="return SomeMethod();"
In the markup. There hopefully is a way to do this with script controls?
Example:
Here's what I have in the script file:
//THIS IS THE METHOD CLICK CALLS
handleLnkDeleteButtonClick: function(e)
{
var confirmed = confirm('This will delete the current Message category and move all messages to the Oprhan cataegory. Continue?');
return confirmed;
},
initialize: function()
{
this._lnkDeleteButton = $get(this._lnkDeleteButtonID);
this._lnkDeleteButton.idpicker = this;
//HOOK BEGINS HERE
this._lnkDeleteButtonClick = Function.createDelegate(this, this.handleLnkDeleteButtonClick);
$addHandler(this._lnkDeleteButton, "click", this._lnkDeleteButtonClick);
//END HOOK HERE
NDI.WebControls.Client.PersonalMessageTypePicker.callBaseMethod(this, 'initialize');
},
dispose: function()
{
$removeHandler(this._lnkDeleteButton, "click", this._lnkDeleteButtonClick);
NDI.WebControls.Client.PersonalMessageTypePicker.callBaseMethod(this, 'dispose');
}
Ok so solved it myself after about way too much time trying to phrase things correctly for google. Turns out there is a method to call so that you don't have to worry about returning true or false.
handleLnkDeleteButtonClick: function(e)
{
var confirmed = confirm('This will delete the currery Message category and move all messages to the Oprhan cataegory. Allow?');
if (!confirmed)
{
e.preventDefault();
}
},
So instead of returning confirmed, I merely had to check it's value and call the e.preventDefault method to stop the click from firing.