Prevent Javascript confirm() on Checkbox State Change - javascript

I have a checkbox (which uses the Bootstrap Switch library to act as an on/off toggle) to activate and deactivate users with the help of AJAX.
When a user unchecks the box this function is fired:
$('.user-status-ckbx').on('switchChange.bootstrapSwitch'...
The confirm() dialog pops up asking the user if he's sure he wants to de/activate the user. If the user clicks 'NO', the button is sent back to its original state using:
$("#" + e.currentTarget.id).bootstrapSwitch('toggleState');
The problem I am having is that each time the toggleState() runs, the switchChange.bootstrapSwitch also runs again. This sents up a non-ending confirm() message which only goes away if the user confirms the message.
Is there an efficient way to prevent the switchChange.bootstrapSwitch method from running based on a real user click vs. a programmatically-generated toggle?
I've already tried:
e.originalEvent !== undefined
and
e.which
as suggested in other similar questions, but none of those work, nor do they even appear in the 'e' object...
<script>
$(".user-status-ckbx").bootstrapSwitch('size', 'mini');
$(".user-status-ckbx").bootstrapSwitch('onText', 'I');
$(".user-status-ckbx").bootstrapSwitch('offText', 'O');
//ajax to activate/deactivate user
$('.user-status-ckbx').on('switchChange.bootstrapSwitch', function(e){
var currentDiv = $("#" + e.currentTarget.id).bootstrapSwitch('state');
if( currentDiv == false){
var confirmed = confirm("Are you sure you wish to deactivate this user? They will no longer be able to access any forms.");
if(confirmed == true){
changeActivationStatus($(this).val());
} else {
$("#" + e.currentTarget.id).bootstrapSwitch('toggleState');
}
} else {
var confirmed = confirm("Are you sure you wish to activate this user? Deactivated users which were previously active will have the same permissions prior to their de-activation unless changed manually.");
if(confirmed == true){
changeActivationStatus($(this).val());
} else {
$("#" + e.currentTarget.id).bootstrapSwitch('toggleState');
}
}
});
function changeActivationStatus(userId){
$.post("{{ path('isactive') }}", {userId: userId})
.done(function(data){
console.log("Finished updating " + userId);
})
.fail(function(){
console.log("User could not be updated");
});
};
</script>

There's a way to prevent the event when switching programmatically.
You have to add options to the Bootstrap switches:
var options = {
onSwitchChange: function (event, state) {
// Return false to prevent the toggle from switching.
return false;
}
};
$(".user-status-ckbx").bootstrapSwitch(options);
And when programmatically switching the button, you'll have to add a second argument:
$("#" + e.currentTarget.id).bootstrapSwitch('toggleState', true);
JSFiddle: https://jsfiddle.net/Ravvy/npz8j3pb/

$(".uid-toggle").change(function (event) {
var option = confirm('Are you sure, you want to change status?');
console.log(`$(this).prop('checked')`);
if (option) {
} else {
if ($(this).prop('checked')) {
$(this).prop('checked', !$(this).prop('checked'));
$(this).parent().removeClass('btn-primary off');
$(this).parent().addClass('btn-danger off');
} else {
$(this).prop('checked', !$(this).prop('checked'));
$(this).parent().addClass('btn-primary off');
$(this).parent().removeClass('btn-danger off');
}
}
});

Related

Is there a listener for input checkbox to execute before change

I am having a checkbox and I could perform some operations when the checkbox is clicked using onchange function. But, what I need is, I have to prompt a popup/warning like, If you click the checkbox, some irreversible change could happen. If the user clicks ok in the popup go on with the onchange function, else if the user clicks cancel, undo the change operation. Is there a way to do this?
var checkbox = document.getElementById('myCheckbox');
checkbox.addEventListener('change', firePrompt);
function firePrompt(e) {
if (e.target.checked) {
setTimeout(function() {
var result = confirm('Proceed?');
if (result) {
alert('User said OK');
} else {
alert('User said no!');
e.target.checked = false;
}
}, 5)
}
}
I had to add a setTimeout as firePrompt was immediately fired and wouldn't display the tick until the User had either clicked OK or Cancel.
Here's a JSFiddle

preventDefault() overruled by window.location

I have process in my website which contains a few steps. To navigate I have "previous" and "next" buttons. These buttons are <a> elements with an href attribute (to visit the previous and next step).
The next button works as a door to the next step, but also to validate some fields in the current step, before it continues.
So this is what happens when clicking the next button:
The href value got saved in a variable $url.
preventDefault() prevents the link from opening the URL.
There are some validation checks done.
If they return "true", the $url will be loaded in window.location.
For some steps I need to do another check to the user with a confirm box. But here comes the problem:
Problem:
When the confirm() returns "false", the user should not go to the next page. But the window.location of function 1 "overrules" the preventDefault() of function 2 now.
1. Default next button function:
$('#next_link').click(function(e) {
var url = $(this).attr('href');
e.preventDefault();
if(wiz_validate_required() && wiz_is_step_done()) {
window.location = url;
}
});
2. Confirm box function:
$('.dimensions-check').click(function(e) {
if(confirm('Have you specified the dimensions in millimeters?') == false) {
e.preventDefault();
}
});
I would do something like that. If you have any question for the code please ask!
fiddle
// These can be changed for each step if you want or not a confirmation
var needs_confirm = true;
var cb_message = 'Have you specified the dimensions in millimeters?';
$('#next_link').click(function(e) {
var url = $(this).attr('href');
e.preventDefault();
if (needs_confirm === true) {
if (confirm_box(cb_message) === true) {
redirect_window(url);
}
} else {
redirect_window(url);
}
});
function confirm_box(cb_message) {
if (confirm(cb_message) === true) {
return true;
} else {
return false;
}
}
function redirect_window(url) {
if (wiz_validate_required() && wiz_is_step_done()) {
window.location = url;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="next_link">link
</div>
Where do you called the dimension-check?
e.preventDefault() only cancel the default action of a button which is submit the form. Regardless of e.preventDefault windows.location will always redirect you.
$('#next_link').click(function(e) {
var url = $(this).attr('href');
e.preventDefault();
if(wiz_validate_required() && wiz_is_step_done()) {
//If dimension isnot prompt{
//windows.location
//}else call dimension prompt
}
});
You can put the windows.location like this:
$('.dimensions-check').click(function(e) {
if(confirm('Have you specified the dimensions in millimeters?') == true) {
window.location = url;
}
});

Javascript onbeforeunload close browser window

I have this tiny script for now that checks if any change is made on the form. If there is a change
then I set a flag to 'Y'. I call this function on onBeforeunload="changeConfirm()" places in the body tag. I know
I can't stop the user from closing down the window, but how do I make this scenario work where he made a change
-> decide to close the window -> Script alerted him -> User clicks cancel (Now I need to bring him back to the screen
instead of closing browser.
<script type="text/javascript">
var Flag= "";
function changeConfirm(){
if(Flag == 'Y')
{
var confirmStatus = confirm('Changes made. Dont want to save?');
}
else {
alert("No changes were made " + Flag);
}
}
</script>
Try this :
function confirmChanges() {
if(Flag == 'Y')
{
if(confirm('Changes made. Dont want to save?')){
return false;
}else{
return true;
}
}
else {
alert("No changes were made " + Flag);
}
}
It should be like this:
window.onbeforeunload = function() {
if ( Flag == 'Y' ) {
return "Changes made. Don't want to save?";
}
}

Making a link confirmation with Jquery alert dialogs plugin

I have the following situation:
-A website with a table where every row represents an item, and for each item there is a link to make certain action (with GET vars).
So, I'm using the Jquery Alert Dialogs Plugin for making a confirmation message, but i can't get to follow the link after the user presses 'OK'
JS Code:
<script type="text/javascript">
var go = false;
$(document).ready( function() {
$("a.disable ").click( function() {
if(go == false) {
jConfirm('Are u sure?', 'Confirm action', function(r) {
if (r == true)
{
go = true;
alert( $(this).attr['href']);
}
});
});
</script>
Note: I'm using alert for testing, but that should be a document.location
Note 1: the alert() gives me 'undefined' :(
Note 2: I'm using multiple buttons with the same class (number of buttons depends on items count)
HTML:
Disable
Note: button repeated with different get vars
Also, if I use "a.disable" selector in the alert(), I got the URL of the first button in the page, so doesn't work :<
Thanks!
<script type="text/javascript">
var go = false;
$(document).ready( function() {
$("a.disable").click( function() {
var $this = $(this); // cached the object $(this)
if(go == false) {
jConfirm('Are u sure?', 'Confirm action', function(r) {
if (r == true)
{
go = true;
alert( $this.attr('href')); // use the cached object
}
});
});
</script>

DropDownList not firing onbeforeunload when AutoPostBack="True"

I have implemented an "unsaved changes" warning using techniques described on these pages:
Client/JS Framework for "Unsaved Data" Protection?
http://kenbrowning.blogspot.com/2009/01/using-jquery-to-standardize.html
This works well except for a DropDownList on the page. It does an AutoPostBack, and I want onbeforeunload to fire because unsaved changes will be lost, but it isn't working. Should it be raising the onbeforeunload event? Can I somehow make it raise the event?
Edit:
The DropDownList is inside an UpdatePanel, so that means it isn't unloading the page and that would be why onbeforeunload isn't being triggered. Is there any way I can trigger the event programmatically? Or do I have to roll my own imitation Confirm dialog?
Edit2
I now have a solution that adds the dialog to asynchronous postbacks from an UpdatePanel. I have edited the original script, adding the call to setConfirmAsyncPostBack() as described in my solution.
Here is my JavaScript:
/****Scripts to warn user of unsaved changes****/
//https://stackoverflow.com/questions/140460
//http://jonstjohn.com/node/23
//Activates the confirm message onbeforeunload.
function setConfirmUnload(on) {
setConfirmAsyncPostBack();
if (on) {
removeCheckFromNoWarnClasses();
fixIEonBeforeUnload();
window.onbeforeunload = unloadMessage
return;
}
window.onbeforeunload = null
}
function unloadMessage() {
return 'You have unsaved changes.';
}
//Moves javascript from href to onclick to prevent IE raising onbeforeunload unecessarily
//http://kenbrowning.blogspot.com/2009/01/using-jquery-to-standardize.html
function fixIEonBeforeUnload() {
if (!$.browser.msie)
return;
$('a').filter(function() {
return (/^javascript\:/i).test($(this).attr('href'));
}).each(function() {
var hrefscript = $(this).attr('href');
hrefscript = hrefscript.substr(11);
$(this).data('hrefscript', hrefscript);
}).click(function() {
var hrefscript = $(this).data('hrefscript');
eval(hrefscript);
return false;
}).attr('href', '#');
}
//Removes warnings from Save buttons, links, etc, that have been can be given "no-warn" or "no-warn-validate" css class
//"no-warn-validate" inputs/links will only remove warning after successful validation
//use the no-warn-validate class on buttons/links that cause validation.
//use the no-warn class on controls that have CausesValidation=false (e.g. a "Save as Draft" button).
function removeCheckFromNoWarnClasses() {
$('.no-warn-validate').click(function() {
if (Page_ClientValidate == null || Page_ClientValidate()) {
setConfirmUnload(false);
}
});
$('.no-warn').click(function() {
setConfirmUnload(false);
});
}
//Adds client side events to all input controls to switch on confirmation onbeforeunload
function enableUnsavedChangesWarning() {
$(':input').one('change', function() {
window.onbeforeunload = function() {
return 'You have unsaved changes.';
}
});
removeCheckFromNoWarnClasses();
}
And in my ASP.NET page, when the user makes a change:
if (changed)
{
...
//Confirm unload if there are unsaved changes.
//NB we also have to call fixIEonBeforeUnload() to fix links, done in in page load to include links that are rendered during callbacks
ScriptManager.RegisterStartupScript(Page, GetType(), "unsavedchanges", "setConfirmUnload(true);", true);
}
else
...
Also see How to prevent AutoPostBack when DropDownlist is selected using jQuery
//http://msdn.microsoft.com/en-us/magazine/cc163413.aspx
//https://stackoverflow.com/questions/2424327/prevent-asp-net-dopostback-from-jquery-submit-within-updatepanel
//Adds an event handler to confirm unsaved changes when an asynchronous postback is initialised by an UpdatePanel
function setConfirmAsyncPostBack() {
if (typeof (Sys.WebForms) === "undefined" || typeof (Sys.WebForms.PageRequestManager) === "undefined")
return;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(confirmAsyncPostBack);
}
//An event handler for asynchronous postbacks that confirms unsaved changes, cancelling the postback if they are not confirmed
//Adds the confirmation to elements that have a css class of "warn"
function confirmAsyncPostBack(sender, args) {
if (window.onbeforeunload != null && args.get_postBackElement().className == "warn" && !unloadConfirmed())
args.set_cancel(true);
}
//Displays a confirmation dialog that imitates the dialog displayed by onbeforeunload
function unloadConfirmed() {
var confirmed = confirm("Are you sure you want to navigate away from this page?\n\n" + unloadMessage() + "\n\nPress OK to continue or Cancel to stay on the current page.");
if (confirmed)
window.onbeforeunload = null;
return confirmed;
}

Categories