Exit confirmation in Javascript with Telerik controls - javascript

I'm using Telerik controls for my project. On my page, there are some links to another page, several radtextboxes and a radbutton (it causes a postback). When the textbox values are changed, the button becomes enabled. Then, in my window.onbeforeunload, I check if the button is enabled or disabled. If it is enabled, then the confirm dialog appears. The code looks like this :
window.onbeforeunload = function (evt) {
var ClientGeneral_btnSave = $find('<%=btnSave.ClientID %>');
if (ClientGeneral_btnSave.get_enabled() == true) {
var message = 'You will lose unsaved data?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
This code works well. When I close the tab, the confirm dialog appears. When I click on the links, it does. But, when I click on the btnSave itself, the dialog appears too, which is unsual. I want the btnSave NOT to cause onbeforeunload event
Please tell me how to do this.
Thank you in advance

It will fire onbeforeunload this if the btnSave posts back which it looks as if it is. Therefore you have a couple of choices
Prevent the btnSave from posting back if you don't need it to. Easiest way to do it is put this attribute in the asp:Button markup
OnClientClick="return false"
Wire up a javaScript/jQuery method to disable the onbeforeunload event. I did this before by stashing an value in a hidden field and using this to signal that the onbeforeunload event should fire.
for instance
$('#<%= btnSave.ClientID %>').bind('click', function(e){
$('#myHiddenFieldId').val('1');
});
and change your on beforeunload handler to check that the hidden field is not equal to 1 (make 0 the default i.e.
window.onbeforeunload = function (evt) {
if( $('#myHiddenFieldId').val() != '1')
{
//your logic here
}
}
You could probably do something better by unbinding the onbeforeunload handler in the btnSave click event using JQuery rather than using a hidden field to override.
Option 2 can get fiddly though - so best of luck

Related

Stop onclick method running with jQuery

I have a button similar to below
<button id="uniqueId" onclick="runMethod(this)">Submit</button>
What I'm trying to do is stop the runMethod from running, until after I've done a check of my own. I've tried using the stopImmediatePropagation function, but this doesn't seem to have worked. Here's my jQuery:
$j(document).on('click', '#uniqueId', function(event) {
event.stopImmediatePropagation();
if(condition == true) {
// continue...
} else {
return false;
}
return false;
});
Note: runMethod basically validates the form, then triggers a submit.
What you want to do, especially in the way that you want to do it, requires a some sort of workaround that will always be a bit fiddly. It is a better idea to change the way the button behaves (e.g. handle the whole of the click event on the inside of the jQuery click() function or something along those lines). However I have found sort of a solution for your problem, based on the assumption that your user will first hover over the button. I am sure you can extend that functionality to the keyboard's Tab event, but maybe it will not work perfectly for mobile devices' touch input. So, bear in mind the following solution is a semi-complete workaround for your problem:
$(document).ready(function(){
var methodToRun = "runMethod(this)"; // Store the value of the onclick attribute of your button.
var condition = false; // Suppose it is enabled at first.
$('#uniqueId').attr('onclick',null);
$('#uniqueId').hover(function(){
// Check your stuff here
condition = !condition; // This will change to both true and false as your hover in and out of the button.
console.log(condition); // Log the condition's value.
if(condition == true){
$('#uniqueId').attr('onclick',methodToRun); // Enable the button's event before the click.
}
},
function(){
console.log('inactive'); // When you stop hovering over the button, it will log this.
$('#uniqueId').attr('onclick',null); // Disable the on click event.
});
});
What this does is it uses the hover event to trigger your checking logic and when the user finally clicks on the button, the button is enabled if the logic was correct, otherwise it does not do anything. Try it live on this fiddle.
P.S.: Convert $ to $j as necessary to adapt this.
P.S.2: Use the Javascript console to check how the fiddle works as it will not change anything on the page by itself.
Your problem is the submit event, just make :
$('form').on('submit', function(e) {
e.preventDefault();
});
and it works. Don't bind the button click, only the submit form. By this way, you prevent to submit the form and the button needs to be type button:
<button type="button" .....>Submit</button>
Assuming there's a form that is submitted when button is clicked.
Try adding
event.cancelBubble();
Hence your code becomes:
$j(document).on('click', '#uniqueId', function(event) {
// Don't propogate the event to the document
if (event.stopPropagation) {
event.stopPropagation(); // W3C model
} else {
event.cancelBubble = true; // IE model
}
if(condition == true) {
// continue...
} else {
return false;
}
return false;
});
Your code is mostly correct but you need to remove J:
$(document).on('click', '#uniqueId', function(event) {...
You also need to remove the onClick event from the inline code - there's no need to have it there when you're assigning it via jQuery.
<button id="uniqueId">Submit</button>

Allowing the Javascript Onbeforeunload Function on the specific button on ASP.NET Framework

How to set the Onbeforeunload Function on the specific button?
Example, I have 3 buttons.
<div>
<asp:Button ID="btnBack" runat="server" Text="Back" CssClass="po-font" Height="30px"/>
<asp:Button ID="btnSumbit" runat="server" Text="Submit" CssClass="po-font" Height="30px"/>
<asp:Button ID="btnSaveToDraft" runat="server" Text="Save To Draft" CssClass="po-font" Height="30px"/>
</div>
On javascript, I did something like:
<script type="text/javascript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "Are you sure you want to leave this page? Any unsaved progress will be lost";
}
</script>
The function will work properly though but I want to specify the function in an specific button probably on the "Back" button. I did something like.
<script type="text/javascript">
function confirmExit()
{
return "Are you sure you want to leave this page? Any unsaved progress will be lost";
}
$('#btnBack').live('click', function () {
window.onbeforeunload = confirmExit;
});
</script>
but Id doesn't work. How to do this? Any Ideas? I just want to trigger the function on the specified button. Help me.
Use $('<%=btnBack.ClientID%>').click(function(){...}); because asp.net prefix its own client with the control id and html rendered id may look like ct100$btnBack.
First off its unlikely that the ID is correct as ASP.NET prefixes the ID with the containers if that object. Either give btnBack a class and use that or:
$("[id$='btnBack']").on("click",...)
I'll edit with a battle tested version when I'm back in front of my pc
* Edit to add battle tested code *
So you need to bind the unload event to the window, you can't assign a function to it as Kevin says in his answer. If you only want it to fire for a specific button, the code below is something I use in active production (it has a few more checks, and checks if anything has been changed on a page before firing etc...), so should work for you:
if (self == top) { // Check we're not in an iFrame or colorbox
$(window).bind("beforeunload", function (event) { // bind the window unload event
if (backLinkClicked) { // Check if the back link has been clicked, if so prompt
return "Are you sure you want to leave this page? Any unsaved progress will be lost";
};
});
}
Then your click handler:
var backLinkClicked = false;
$("[id$='btnBack']").click(function() { backLinkClicked = true });
So you back button click handler just changes the variable to fire the prompt on unload.
First off, you should understand that onbeforeunload is an event, and by putting:
window.onbeforeunload = confirmExit;
you are attaching an event handler to window, which will be global.
If I am correct, what you want is bringing up a confirmation dialog when user tries to navigate away by clicking on a button. I suggest you try this:
$('#<%=btnBack.ClientID%>').on('click', function (e) {
// check if user clicked cancel
if (!confirm("Are you sure [...]") {
e.stopImmediatePropagation();
e.preventDefault();
return false;
}
});
With this, when user clicks the button, a confirmation dialog will appear (confirm()). If user clicks cancel, code will call stopImmediatePropagation() (which should prevent other JS event handler from running) and preventDefault() (which disable the default action when the button is clicked, e.g., submitting the form).
I haven't tested this out myself, but I guess it should work.

onbeforeunload keeps poping up an alert box when user click something

I am created a page that warns the user when they click on the (close x) button on the window. I did some reading and discovered that JavaScript had a function called onbeforeonload which can take of the job I was trying to achieve. I however found at after my implementation that, when a user clicks on anything in my window (example: save and enter) The dialog box reappears. I was wondering how I could only target the specific X button in the window.
window.onbeforeunload = function (evt) {
var message = 'Do you want to leave?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
Right now the function is being called globally... this resource might help you achieve what you are looking for: http://randomdrake.com/2009/09/23/how-to-use-onbeforeunload-with-form-submit-buttons/
This is a "working as intended" behavior for IE. Anchor tag clicks, regardless of whether they navigate or not, will trigger the onbeforeunload event.
This is the workaround I used - I am not sure whether it is the best approach or not:
document.onmouseup = function () {
if (window.event.srcElement.tagName === 'A') {
// turn off your onbeforeunload handler
...
// some small time later, turn it back on
setTimeout(..., 200);
}
};

window.onbeforeunload - Only show warning when not submitting form [duplicate]

This question already has answers here:
How to disable beforeunload action when user is submitting a form?
(7 answers)
Closed 7 years ago.
I am using window.onbeforeunload to prevent the user from navigating away after changing values on a form. This is working fine, except it also shows the warning when the user submits the form (not desired).
How can I do this without showing the warning when the form submits?
Current code:
var formHasChanged = false;
$(document).on('change', 'form.confirm-navigation-form input, form.confirm-navigation-form select, form.confirm-navigation-form textarea', function (e) {
formHasChanged = true;
});
$(document).ready(function () {
window.onbeforeunload = function (e) {
if (formHasChanged) {
var message = "You have not saved your changes.", e = e || window.event;
if (e) {
e.returnValue = message;
}
return message;
}
}
});
Using the form's submit event to set a flag might work for you.
var formHasChanged = false;
var submitted = false;
$(document).on('change', 'form.confirm-navigation-form input, form.confirm-navigation-form select, form.confirm-navigation-form textarea', function (e) {
formHasChanged = true;
});
$(document).ready(function () {
window.onbeforeunload = function (e) {
if (formHasChanged && !submitted) {
var message = "You have not saved your changes.", e = e || window.event;
if (e) {
e.returnValue = message;
}
return message;
}
}
$("form").submit(function() {
submitted = true;
});
});
you could use .on() to bind onbeforeunload and then use .off() to unbind it in form submission
$(document).ready(function () {
// Warning
$(window).on('beforeunload', function(){
return "Any changes will be lost";
});
// Form Submit
$(document).on("submit", "form", function(event){
// disable warning
$(window).off('beforeunload');
});
}
You can handle the submit() event, which will occur only for your form submission.
Within that event, set your flag variable formHasChanged to false to allow the unload to proceed. Also, just a suggestion, but since the purpose of that flag variable will have changed, so you may want to rename it something like 'warnBeforeUnload'
$(document).submit(function(){
warnBeforeUnload = false;
});
I was looking for a better solution to this. What we want is simply exclude one or more triggers from creating our "Are you sure?" dialog box. So we shouldn't create more and more workarounds for more and more side effects. What if the form is submitted without a click event of the submit button? What if our click-handler removes the isDirty status but then the form-submit is otherwise blocked afterwards? Sure we can change the behaviour of our triggers, but the right place would be the logic handling the dialog. Binding to the form's submit event instead of binding to the submit button's click event is an advantage of the answers in this thread above some others i saw before, but this IMHO just fixes the wrong approach.
After some digging in the event object of the onbeforeunload event I found the .target.activeElement property, which holds the element, which triggered the event originally. So, yay, it is the button or link or whatever we clicked (or nothing at all, if the browser itself navigated away). Our "Are you sure?" dialog logic then reduces itself to the following two components:
The isDirty handling of the form:
$('form.pleaseSave').on('change', function() {
$(this).addClass('isDirty');
});
The "Are you sure?" dialog logic:
$(window).on('beforeunload', function(event) {
// if form is dirty and trigger doesn't have a ignorePleaseSave class
if ($('form.pleaseSave').hasClass('isDirty')
&& !$(event.target.activeElement).hasClass('ignorePleaseSave')) {
return "Are you sure?"
}
// special hint: returning nothing doesn't summon a dialog box
});
It's simply as that. No workarounds needed. Just give the triggers (submit and other action buttons) an ignorePleaseSave class and the form we want to get the dialog applied to a pleaseSave class. All other reasons for unloading the page then summons our "Are you sure?" dialog.
P.S. I am using jQuery here, but I think the .target.activeElement property is also available in plain JavaScript.

Detecting form changes using jQuery when the form changes themselves were triggered by JS

I have a list of radio buttons that I can toggle "yes" or "no" to using Javascript.
$(document).ready(function(){
$('#select-all').click(function(){
$('#notifications .notif-radio').each(function(){
$('input[type="radio"]', this).eq(0).attr('checked', true);
$('input[type="radio"]', this).eq(1).attr('checked', false);
});
});
$('#deselect-all').click(function(){
$('#notifications .notif-radio').each(function(){
$('input[type="radio"]', this).eq(0).attr('checked', false);
$('input[type="radio"]', this).eq(1).attr('checked', true);
});
});
});
this works just fine. Now I have a separate piece of code that detects when a user has changed something, and asks them if they want to leave the page.
var stay_on_page;
window.onbeforeunload = confirm_exit;
$('.container form input[TYPE="SUBMIT"]').click(function(){
stay_on_page = false;
});
$('#wrapper #content .container.edit-user form').change(function(){
stay_on_page = true;
});
function confirm_exit()
{
if(stay_on_page){ return "Are you sure you want to navigate away without saving changes?"; }
}
The problem is that if the user uses the first piece of functionality to toggle all radio buttons one way or another. The JS detecting form changes doesn't see that the form was changed. I have tried using .live, but to no avail. Anyone have any ideas?
I do something similar to this by adding change() (or whatever's appropriate, click() in your case I suppose) event handlers which set either a visible or hidden field value, then check that value as part of your onbeforeunload function.
So, my on before unload looks like:
window.onbeforeunload = function () {
if ($('#dirtymark').length) {
return "You have unsaved changes.";
}
};
And, or course, dirtymark is added to the page (a red asterisk near the Save button), when the page becomes dirty.

Categories