I want to show an alert if user has entered a qty in a input field on the page for adding a product but instead of adding it to the cart clicks on some other action. In that case I want user to confirm his action.
But returning a string from the handler function for onbeforeunload
is having no effect on the alert shown by both chrome(version 53.0.2785.89 (64-bit)) and firefox(version 48) on Ubuntu.
Code is below:
<script>
(function($){
var confirmOnPageExit = function (e){
// If we haven't been passed the event get the window.event
e = e || window.event;
var message = 'Are you sure you don\'t want to add these item(s) to cart?';
// For IE6-8 and Firefox prior to version 4
if (e)
{
e.returnValue = message;
}
// For Chrome, Safari, IE8+ and Opera 12+
return message;
};
function isAnyInputHasValue(){
var hasSomeQty = false;
var qtyInputs = $('input.qty');
if(qtyInputs.length > 0){
qtyInputs.each(function(){
if($(this).val().length > 0){
hasSomeQty = true;
return false;
}
});
}
return hasSomeQty;
}
$(document).ready(function(){
var shouldConfirm = isAnyInputHasValue();
if(shouldConfirm){
window.onbeforeunload = confirmOnPageExit;
//$(window).on('beforeunload', confirmOnPageExit);
}else{
window.onbeforeunload = '';
}
console.log('on page load ', shouldConfirm);
});
$(document).on('change', 'input.qty', function(){
var shouldConfirm = false;
if($(this).val().length > 0){
shouldConfirm = true;
}else{
shouldConfirm = isAnyInputHasValue();
}
if(shouldConfirm){
window.onbeforeunload = confirmOnPageExit;
}else{
window.onbeforeunload = '';
}
console.log('on qty change ', shouldConfirm);
});
})(jQuery);
</script>
Same code seems to work for others who previously asked same question on stackoverflow. Also tried to use jQuery .on
method to subscribe to onbeforeunload
event with no success.
I have prepared a fiddle to demonstrate the problem: