I'm using jQuery UI to present a dialogue box asking, "Do you really want to perform this action?" when a user clicks on a hyperlink or a form button.
If the user clicks "Confirm" then I want to perform the original default action.
Here is my code:
[html]
Click me
[jquery]
// Global variable keeps track of whether the user has clicked confirm
var confirmed = false;
$("a").on("click", function(e) {
var self = $(this);
var options = {
autoOpen: true,
modal: true,
title: "Confirmation Required",
buttons : {
"Confirm" : function() {
// The user has confirmed, so set global variable to true
confirmed = true;
// Re-trigger the click
self.trigger("click");
},
"Cancel" : function() {
$(this).dialog("close");
}
}
};
// If the user hasn't yet confirmed, display the dialogue box
if (confirmed == false) {
$("<div />").text("Are you sure you want to do this?").dialog(options);
// Prevent the default action
e.preventDefault();
}
// Otherwise the user has confirmed, so don't preventDefault and return true
else {
confirmed = false;
// Alert here to check we reached this point
alert("Returning true");
return true;
}
});
When first clicking the link, the default action is prevented and the dialogue box opens.
When clicking "Confirm" in the dialogue box, the click event is triggered again, and the alert box fires saying, "Returning true". All good so far, however the page doesn't load. So for some reason second time around the default event is still prevented and I can't for the life of me figure out why.
This is most likely due to the fact the dialog is still open. However even if you close it, you will not be able to click the a element like this.
trigger('click') only triggers the function which is bond to the click event in jQuery and if you would use $el.click(), I think it only supports format <a onclick="func()">Click here</a>
How I solved this; On the dialog confirmation I update the window location with jQuery based on the <a> elements href.
Please see working snippet below;
Click me
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var confirmed = false;
$("a").on("click", function(event) {
var $self = $(this);
if (!confirmed) {
event.preventDefault();
$("<div />").text("Are you sure you want to do this?").dialog({
autoOpen: true,
modal: true,
title: "Confirmation Required",
buttons : {
"Confirm" : function() {
window.location.href = $self.attr('href');
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
}
});
});
</script>
Related
I have a page where I want to configure dates by selecting dates with date picker and add to dynamic table using javascript in same page.
I have multiple dates in the table but not saved or not clicked submit button yet but clicked on sub tab in same page to navigate to another page and a popup opened saying you have unsaved changes
Clicked on stay on same page and the added dates are present on the table and clicked on submit button.
Why instead of submitting the form, it redirects to previously visited tab(sub tab mentioned in step 2)?
Below code is to warn, if there is unsaved data:
var submitted = false;
$(document).ready(function() {
$('#addDates').click( function() {
submitted=true;
});
window.onbeforeunload = function () {
if (!submitted) {
return 'Do you really want to leave the page?';
} else {
window.onbeforeunload = null;
}
}
});
maybe try to overwrite the event with an empty function:
var submitted = false;
$(document).ready(function() {
$('#addDates').click( function() {
submitted=true;
});
window.onbeforeunload = function () {
if (!submitted) {
return 'Do you really want to leave the page?';
} else{
window.onbeforeunload = function() {};
}
}
});
I have a function that asks users for confirmation when selecting a value from a Select dropdown. When using the regular JavaScript confirm(), the change event does not get the newly selected value without clicking on confirm. This can be seen in this Fiddle.
When a value is selected, and the user clicks cancel, the same value is shown in an alert dialog. When the user clicks confirm, the newly selected value is displayed.
However, I'd like to use SweetAlert. When changing the value with SweetAlert, the change happens without even selecting confirm or cancel. As demonstrated in this Fiddle. When a value is selected, an alert dialog is displayed right after selection, unlike with the pure JS Confirm() which blocks the event somehow.
I'd like to achieve the same effect as the JS confirm(), where the change event is not triggered while the user has not clicked confirm or cancel, when using SweetAlert.
Aside from both Fiddles which demonstrate the problem, here's the code I'm using:
Some simple HTML select:
<select id="dropdownId">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
The JavaScript confirm() version (which does what it needs to do):
var prev_val;
$('#dropdownId').focus(function () {
prev_val = $(this).val();
}).change(function (e) {
var select = this;
$(this).blur();
var success = confirm('Are you sure you want to change the Dropdown?');
if (success) {
// Other changed code would be here...
} else {
$(this).val(prev_val);
return false;
}
});
$('#dropdownId').change(function (e) {
alert($(this).val());
});
And the SweetAlert version, where the change event should wait on the response of the SweetAlert dialog.
var prev_val;
$('#dropdownId').focus(function () {
prev_val = $(this).val();
}).change(function (e) {
var select = this;
$(this).blur();
return swal({
title: "Are you sure?",
text: "Change dropdown select?",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes!",
cancelButtonText: "No!",
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
return true;
} else {
$(select).val(prev_val);
return false;
}
});
});
$('#dropdownId').change(function (e) {
alert($(this).val());
});
Edit:
Moving the logic to the confirm handler of the dialog does not solve this issue. I'm using a framework (Apache Tapestry) which listens for a change event on the select. When using the solution as RRR stated, in this fiddle, the change event still happens. Which still causes it to fire an event to my backend, unlike with the JS confirm() which does not change the value until confirm was clicked.
Edit 2:
My problem doesn't really seem to be that clear. Here are the steps I undertake to try and show what the root of the problem is:
When using the JS confirm from this fiddle. The following happens:
I click on a value
It asks for confirmation
On confirm, it logs the new value. On cancel, it logs the original value.
When using the SweetAlert dialog, using this fiddle. The following happens:
I click on a value
It logs the newly selected value, before confirming/cancelling
On confirm/cancel I can execute logic.
When using the SweetAlert dialog, as edited by RRR in this fiddle. The following happens:
I click on a value
It logs the newly selected value, before confirming/cancelling
On confirm/cancel, it shows an alert
Both my and RRR's SweetAlert example have the same issue. Namely, step 2. Not the fact that it logs, but the fact that the value actually changes. Unlike in the first pure JS example, where the value does NOT change unless confirm is clicked.
Ok. Here is the issue.
You call 2 different actions at onchange event:
1- The big function...
2- A test alert.
Both occur at the same time. <-- Here lies the confusion!
This is why it appeared to you that swal doesn't "wait" to get an answer from the user.
Try this... And look at your console.log messages:
var prev_val;
$('#dropdownId').focus(function () {
prev_val = $(this).val();
console.log("On focus event value : "+prev_val); // ADDED
}).change(function (e) {
var select = this;
console.log("At the BEGINNING of the change event : "+$(select).val()); // ADDED
$(this).blur();
swal({ // REMOVED return in front of it
title: "Are you sure?",
text: "Change dropdown select?",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes!",
cancelButtonText: "No!",
closeOnConfirm: true, // These are default.. useless to specify
closeOnCancel: true // These are default.. useless to specify
},
function (isConfirm) {
if (isConfirm) {
//return true; // no need to return anything - commented out
console.log("swal YES");
console.log("At the END of the change event : "+$(select).val());
} else {
$(select).val(prev_val);
//return false; // no need to return anything - commented out
console.log("swal NO");
console.log("At the END of the change event : "+$(select).val());
}
// Here is a callback final test alert!
alert("Callback alert: "+$(select).val());
});
});
/*$('#dropdownId').change(function (e) { // This was a bad idea ! ;)
alert($(this).val());
});*/
In my case sweet alert 2 was blocking my binded event handlers:
Swal.fire( // Not works - Nothing will happen onclick
{html: `<button id="btn1" onclick="alert('clicked')">Delete</button>`,
)
So i binded the event handlers in javascript instead, on modal open:
Swal.fire(
{html: `<button id="btn1">Delete</button>`,
onOpen: () => {document.querySelector('#btn1').onclick = () => {alert('clicked')}
)
So, this code is working:
<script>
$(document).ready(function(){
var btn = $('#submit_send_order');
btn.attr({disabled: 'disabled'});
var chk = $('.end-box');
chk.click(function(){
if ($(this).attr('checked'))
btn.removeAttr('disabled');
else
btn.attr({disabled:'disabled'});
});
});
</script>
but I can't get any working version of a click, onclick, or event handler to cause a popup message during the else condition. Unless users checks a box, they cannot send their order on my site. Right now they click the button and nothing happens until they check the box. But I'd like an alert to show as well, e.g.:
$(document).ready(function(){
$('#submit_send_order').click(function(){
alert("You cannot proceed until you check the end box");
});
});
As Verhaeren said above, if the button is disabled, then it can't fire the click event. Rather than disabling the button, I would just put an if/else check in the click event.
So...
$(document).on('click', '#submit_send_order', function(event) {
event.preventDefault();
if ($('.end-box').prop('checked')) {
//Handle form submission
} else {
alert('You cannot proceed until you check the end box');
}
});
The onclick event doesn't fire when the element is disabled. Also, notice which is the right method to see if the checkbox is checked:
$(document).ready(function(){
var btn = $('#submit_send_order');
btn.attr({disabled: 'disabled'});
var chk = $('.end-box');
chk.on('click', function(){
if ($(this).is(':checked'))
btn.removeAttr('disabled');
else
btn.attr({disabled:'disabled'});
});
btn.on('click', function(){
alert("You cannot proceed until you check the end box");
});
});
I build a "solution" for this if you REALLY whant to do that. You can check it at this fiddle:
http://jsfiddle.net/2f1wsb8c/3/
It's placing an element with the same size of the button over it to catch the click when the button is disabled.
I am super novice and need a quick advice. I have installed a javascript based popup plugin on my wordpress site, witch opens automatically when somebody visits the site. To close the popup the user will have to click a cross X in the corner of the popup.
I need to edit the plugin so that the user can click ANYWHERE, and the plugin will close.
Here is the javascript code I found. any tips about this?
function open_lightbox(){
//var closebut = (typeof(ujiPopups) !== 'undefined' && ujiPopups != null && ujiPopups.showclose && ujiPopups.showclose == "true") ? true : false;
jQuery("#popup").modal({
onOpen: function (dialog) {
dialog.overlay.fadeIn('fast');
dialog.data.hide();
dialog.container.show('fast', function () {
dialog.data.fadeIn('slow');
});
},
autoResize: false,
autoPosition: true,
escClose: false,
zIndex: 999999,
overlayClose: false
});
}
function popups_close(){
jQuery.modal.close();
jQuery("#popup").remove();
}
Something like this should do it:
$(document).click(function() {
if($('#popup').is(':visible')) {
popups_close();
}
});
If you wish to keep the modal active on interaction with the popup itself:
$(document).click(function(e) {
if (!$(e.target).is("#popup")) {
if ($('#popup').is(':visible')) {
popups_close();
}
}
});
A simple example here: http://jsfiddle.net/wnT4G/
*Check comments for some elegant revisions by #ComFreek
I use a rather strange method, but it works:
$('.click-btn').click(function(){
$('.modal').show(); //show popup
})
$('body').click(function(){
$('.modal').hide(); //hide modal
})
$('.click-btn, .modal').click(function(e){
e.stopPropagation; // don't close modal by clicking inside modal and by clicking btn
})
user event
function addEvent(action) {
$("body").click(function() { action();});
}
function clearEvent() {
$("body").off('click');
}
You want to do this:
$(document).click(function()
{
popups_close();
})
$('Your selector of the popup').click(function(e)
{
e.stopPropagation();
})
.stopPropagation(); Will actually cancel the .click() function that was triggerd by clicking in the document.
So whenever you click anywere in the document the popup will close, except when clicked on the popup itself.
Hope this helped!
jsFiddle
I think you just want to set overlayClose and possibly escClose to true. Your plugin probably creates an overlay on the page so users can't click anywhere else so I'm guessing overlayClose: true will get the plugin to close the dialog when the overlay is clicked.
escClose: true,
overlayClose: true
I'm not sure what plugin you're using, but this one uses a clickClose property.
There are similar questions but they could not help me solve this.
When the dialog opens and I press enter, I want this to be equivalent to closing the dialog.
I have written the following but it does not work. Instead, at every ENTER, the focus stays on the element that triggers the opening of the dialog, giving rise to multiple instances.
Thanks
var $dialogError = $('<div id="dialogError"></div>').html(vGraph.getLastErrorMsg()).dialog({
autoOpen: false,
open: function() {
$("#dialogError").keydown(function(e) {
alert("enter");
if (e.keyCode == $.ui.keyCode.ENTER) {
$(this).dialog("close");
}
});
},
title: 'Error'
});
$dialogError.dialog('open');
Maybe set the focus to the dialogError element using $('#dialogError').focus(); after opening the dialog, that way the focus is no longer on the element that opened the dialog, and it will capture the enter key.
$(document).on('keypress', function(event) {
if (event.keyCode == $.ui.keyCode.ENTER) {
$('#dialogError').dialog('close');
}
});
This will work regardless of whether the dialog has focus or not which is probably what you want. This code will execute when the dialog is not open, but running $('#dialogError').dialog('close'); will have no adverse effects.
Example - http://jsfiddle.net/tj_vantoll/x32zC/1
try returning false from the keydown handler:
open: function() {
$("#dialogError").keydown(function(e) {
alert("enter");
if (e.keyCode == $.ui.keyCode.ENTER) {
$(this).dialog("close");
return false;
}
});
},