warning popup when user try to move on other page - javascript

I am trying to show the warning popup when user try to move on other page without saving the date.
i am using asp .net mvc 5 bootstroup menu.popup is coming but unable to stop loading other page while navigation to other page.
I need to navigate the user when they clicks Ok button if they click Cancel then they stays the same page.
$(".dropdown-menu").on("click", "li", function() {
var newMenu = $('a', this).attr('href');
var confirm = bootbox.confirm({
message: 'Rule is not saved, Do you want to save it?',
buttons: {
confirm: {
label: 'Continue without saving'
},
cancel: {
label: 'Save and Exit'
}
},
callback: function(result) {
if (result == true && is_dirty == false) {
window.location.href = newMenu;
} else {
window.stop();
}
}
});
});

You can achieve confirmation and achieve what you said using a flag which is set true when the data is saved. Enable the button or link only if flag is set true
$('#btnfb').click(function(){
var r = confirm("press ok to continue!");
if (r == false) {
return false;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Visit W3Schools!

Related

How to display a confirm box before submitting a form using jquery confirm?

I have a form and I want to show a confirmation massage after clicking submit button and also I don't want to use following method
return confirm("Are You Sure?")
I used JQuery Confirm as following.
#using (#Html.BeginForm("SubmitTest", "HydrostaticReception", FormMethod.Post, new {id="ReceptionForm", onsubmit = "ValidateMyform(this);" }))
{
.....
<button onclick="SubmitMyForm()">Submit</button>
}
The javascript codes are ...
function ValidateMyform(form) {
// get all the inputs within the submitted form
var inputs = form.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
// only validate the inputs that have the required attribute
if (inputs[i].hasAttribute("required")) {
if (inputs[i].value == "") {
// found an empty field that is required
alert("Fill all fields");
return false;
}
}
}
return true;
}
The Javascript code for showing Confirm Box (According JQuery Confirm) is
function SubmitMyForm() {
$.confirm({
title: 'Confirm!',
content: 'Are you sure?',
buttons: {
No: function () {
return true;
},
Yes: function () {
$("#ReceptionForm").submit();
//alert("For Test");
//document.getElementById("ReceptionForm").submit();
}
}
});
}
The Problem IS...
When I click Submit button it doesn't wait for me to click Yes button in Confirm box and the form will submit (the Confirm box appears and after 1 sec disappear and form submits).
But when I use alert("For Test"); instead of $("#ReceptionForm").submit(); , it works correctly. Does anybody knows why I'm facing this problem?!!!
You could use a "flag" to know if the confirmation occured or not to "prevent default" submit behavior.
Remove the inline onsubmit = "ValidateMyform(this);" and use a jQuery event handler instead.
var confirmed = false;
$("#ReceptionForm").on("submit", function(e){
// if confirm == true here
// And if the form is valid...
// the event won't be prevented and the confirm won't show.
if(!confirmed && ValidateMyform($(this)[0]) ){
e.preventDefault();
$.confirm({
title: 'Confirm!',
content: 'Are you sure?',
buttons: {
No: function () {
return;
},
Yes: function () {
confirmed = true;
$("#ReceptionForm").submit();
}
}
});
}
});

Prevent Javascript confirm() on Checkbox State Change

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');
}
}
});

JavaScript Pop up problme before navigating away from a page

The code below call the "Click Save!" pop up if there were changes to input fields and someone attempts to navigate away from the page without clicking the submit button to save.
Can someone tell me how to make a small change to this that will call the "Click Save!" pop up for ANY attempt to navigate away from the page even if no changes were made to any of the input fields (but of course still no popup if they click the submit button)?
var warnMessage = "Click Save!";
$(document).ready(function() {
$('input:not(:button,:submit),textarea,select,text').change(function () {
window.onbeforeunload = function () {
if (warnMessage != null) return warnMessage; }});
$('input:submit').click(function(e) {
warnMessage = null;
});
});
var warnMessage = false;
window.onbeforeunload = function (event) {
if (!warnMessage) {
return;
}
else {
return "You have unsaved changes on this page. If you wish to save these changes, stay on the current page.";
}
}
$(document).ready(function () {
$('input:not(:button,:submit),textarea,select,text').change(function (event) {
warnMessage = true;
});
$('input:submit').click(function () {
warnMessage = false;
});
});

How may I return true or false when I click on confirm dialog button?

I have a snippet of jQuery
$(function () {
$('.checked').click(function (e) {
e.preventDefault();
var dirtyvalue = "Test1";
var textvalue= "Test";
if (dirtyvalue.toLowerCase() != textvalue.toLowerCase()) {
{
var dialog = $('<p>Do you want to save your changes?</p>').dialog({
buttons: {
"Yes": function () {
dialog.dialog('close');
alert('yes btn called');
},
"No": function () {
dialog.dialog('close');
alert('No btn called');
},
"Cancel": function () {
dialog.dialog('close');
}
}
});
}
return false;
}
return true;
});
});
I want to return true or false on button click; 'Yes' should return true, 'No' should return true, and 'Cancel' should return false.
I already checked this link, but this is not solving my problem.
See also my previous question.
My scenario is that I have many ActionLink and TreeView links which navigate to their respective pages. Suppose I am on page 1 where I have this JS, and on that page I have many action links. Clicking on page 2, at that time my confirm should open, and when I click on the button 'No' it should redirect to page 2.
A dialog can't return a value, you must put what you want to do in another function. for example
var dialog = $('<p>Are you sure?</p>').dialog({
buttons: {
"Yes": function()
{
alert('you chose yes');
//call a function that redirects you
function_redirect(true);
},
"No": function()
{
alert('you chose no');
//call a function that redirects you
function_redirect(true);
},
"Cancel": function()
{
alert('you chose cancel');
//just close the dialog
dialog.dialog('close');
}
}
});
var function_redirect = function(redirect){
if(redirect === true){
//redirect to page2
}
}
you should put the logic you need to implement in "function_redirect" (or in whatever function you want) and pass parametrs according to the button pressed
EDIT - if you need to know what button has been clicked, just use the event object that is passed to the function
"Yes": function(e) {
//e.target is the element of the dom that has been clicked
//from e.target you can understand where you are and act accordingly
//or pass it to function_redirect
function_redirect(true, e.target);
var function_redirect = function(redirect, target){
if(redirect === true){
if($(target).parent().attr('id') === 'page2'){
//redirect to page2
}else{
//do something else
}
}
}
Dialog works async. So you cant return any value. You should use callback function.
$("a").click(dialog.dialog("open"),function(data){
//do your redirect here
})

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>

Categories