Javascript/JQuery Callback confusion - javascript

I've a Modal which I show for confirmation:
<div class="modal" tabindex="-1" role="dialog" id="modal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
... Body ...
<div class="modal-footer">
<button type="button" id="btnCancel" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" id="btnOk" class="btn btn-primary" data-dismiss="modal">Ok</button>
</div>
</div>
</div>
</div>
Here is the code for showing the above Modal..
var M = {
confirm: function(body, yes, no) {
$('#btnCancel').on('click', function() {
$('#btnCancel').off();
$('#confirm-modal').modal('hide');
if (no) {
return no();
}
});
$('#btnOk').on('click', function() {
$('#btnOk').off();
$('#modal').modal('hide');
if (yes) {
return yes();
}
});
}
}
And here is how I am using it... (In any view for example)
M.confirm("Body", function(){
// Function Body
})
Now, the problem is: If I call confirm, it shows the Modal. But if I click Cancel and than again call confirm and this time, I hit OK: the function (second param in the snippet above) is called twice. If I hit cancel 10 times, the function above is called 10 times.
Any idea why this is happening?
Thank You.

Every time you call confirm you add an event handler to each of btnCancel and btnOk.
However, you only remove the effect handler on one of those buttons when that button is clicked.
So if you call confirm, then click btnCancel, then call confirm you'll have two event handlers on btnOK: One from the first call to confirm and once from the second.
When either button is clicked you need to remove both event handlers.
… or just add the event handlers when the document is loaded and don't touch them thereafter.

Related

Javascript cookie dismiss forever

I have modal pop-up that asks users if they would like to subscribe to my newsletter. If the user closes the modal I don't want it to appear again. Using my code below the pop-up is shown frequently multiple times a day. What would I need to add so that once dismissed the pop-up wouldn't appear again?
//custom.js
if (!readCookie("close_subcribeModal")) {
function subcribeModal() {
$("#subcribeModal").modal("show");
}
setTimeout(function () {
subcribeModal();
}, 5000);
}
Web page:
#if(!isset($_COOKIE['close_subcribeModal']) && #$_COOKIE['close_subcribeModal'] != "1")
<div id="subcribeModal" tabindex="-1" role="dialog" aria-labelledby="subcribeModalLabel" aria-hidden="true">
<div role="document">
<div class="modal-content">
<button type="button" id="subcribeModal__close" class="cancel" data-dismiss="modal" aria-label="Close"></button>
<div class="modal-body">
<h2 class="title">Welcome</h2>
<p>Would you like to receive our weekly newsletter?</p>
<x-mail.newsletter-subscription />
</div>
</div>
</div>
</div>
#endif
It looks like you are using Bootstrap, when the modal window gets hidden (or closed) the event hidden.bs.modal gets triggered.
So we create a cookie if the event occurs (add this on the bottom of your view)
$("#subcribeModal").on('hidden.bs.modal', function() {
Cookies.set('modalShowed','active');
});
Change if (!readCookie("close_subcribeModal")) to if(Cookies.get('modalShowed') != 'active')
and get rid of this if statement #if(!isset($_COOKIE['close_subcribeModal']) && #$_COOKIE['close_subcribeModal'] != "1") on your view.

Modal won't close and prevent default on no click, and won't execute func on yes click

I have a modal with two buttons. One is a yes button and one is a no button. If yes button is pressed, I would like the remainder of the function to execute. If no btn clicked, I would like the page to prevent default and not execute. However, it seems that regardless of which button is clicked, nothing happens besides the modal closing. I am using a modal example I found elsewhere, so this may be the issue. After glancing at it for some time I cannot seem to find where the issue is. Am I missing something small? Or perhaps my Jquery is wrong? Below is my code:
Modal:
<!-- Modal for delete-->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content border-primary mb-3 box-shadow-none img-responsive">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="card-body bg-light">
<div id="del" class="center">
<label>Are you sure you want to delete?</label>
</div>
</div>
<div class="modal-footer">
<div id="deleteYes">
<button type="button" class="btn btn-default" data-dismiss="modal" id="deleteYes">Yes</button>
</div>
<div id="deleteNo">
<button type="button" class="btn btn-default" data-dismiss="modal" id="deleteNo">No</button>
</div>
</div>
</div>
</div>
</div>
And here is my Jquery:
$(".btnDeleteTerminalCommand").click(function (e) {
$("#deleteModal").modal('toggle');
if ($("#deleteNo").click) {
return e.preventDefault();
}
var rowId = "#" + $(this).data("rowindex");
var row = $(rowId);
var termId = row.find(".tdTermId").html().trim();
var cmdId = row.find(".tdCmdId").html().trim();
var cmdVal = row.find(".tdCmdVal").html().trim();
var cmdID = row.find(".cmdID").html().trim();
var data = {
TerminalID: termId,
CommandID: cmdId,
CommandValue: cmdVal,
ID: cmdID
};
$.ajax({
url: '#Url.Action("DeleteTerminalCommand", "TerminalCommand")',
type: "POST",
data: data,
success: function (response) {
console.log("Success");
window.location.href = response.Url;
}
});
});
Any advice helps! Thank you!
Your click handler will toggle the modal and immediately continue to execute the rest of the function before the user can click anything. If your modal has two buttons, create a click handler for each button. Perhaps the No button just closes the modal. The Yes button handler can execute the actions required to accomplish the task.
$(".btnDeleteTerminalCommand").click(function(e){
$("#deleteModal").modal('toggle');
}
$("#deleteNo").click(function(e){
$("#deleteModal").modal('hide');
}
$("#deleteYes").click(function(e){
// build data object
// ajax post
}

Invoke Ajax function from Bootstrap modal button

I'm looking to invoke an ajax function after clicking an option from a bootstrap confirmation modal. the confirmation modal will be open through function remove(parameter)
Any help will be appreciated
function remove(parameter){
// $("#remove-modal").modal('show');
/*
if( modal clicked Yes){
..perform ajax call using 'parameter'
}
*/
}
<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true" id="remove-modal">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Do you want to remove this item?</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="modal-btn-si">Yes</button>
<button type="button" class="btn btn-primary" id="modal-btn-no" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
You could just add an event listener for the yes button.
As the event varies every time the modal is shown you remove it before adding the new one.
remove(parameter) {
var yesButton = $("#modal-button-si");
yesButton.off("click");
yesButton.click(function(){
//perform ajax here
});
}
I would assume adding a click handler to the "Yes" button, after the modal is shown, should work. Something like:
function remove(parameter){
// show the dialog
var m = $("#remove-modal").modal('show');
// find the button in your modal, and attach an event
// handler to it's click event
m.on('shown.bs.modal', function(){
m.find('#modal-btn-si').on('click', function(e){
// do something here...
// When you're ready to dismiss the modal, call:
//
// m.modal('hide');
//
// Make sure this is in the callback for your
// AJAX event, unless you want the modal dismissed
// as soon as the button is clicked
});
});
}

How can I handle the alert (leave or cancel) on page close using Angular 5?

When the page close is triggered by the user, the JS alert pop-up is displayed.
Now how can I handle whether the user has clicked the leave or cancel button
On leave the unload event will be triggered. I am not sure if it possible to catch the cancel properly.
const confirmed = window.confirm('are you sure?');
if (confirmed) {
// user confimed
} else {
// user did not confirm
}
If you want to prevent users from leaving the page you must add canDeactivate guard to that component route definition.
More on it here
Here is my code main.html
<html>
<div class="row">
<div class="col-sm-3 columns">
<button type="" class="btn btn-info" ng-click=“submit()”> Submit </button>
</div>
</html>
this is the main html page once the submit is pressed the respective submit function will be called.
Here is my AlertpopupModal.html
<html>
<script type="text/ng-template" id="AlertpopupModal.html">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Do you want to leave this site</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<p> Changes that you made may not be saved </p>
<button type="button" class="btn btn-default pull-left"
ng-click ="leave()">Leave</button>
<button type="button" class="btn btn-default pull-left"
ng-click="cancel()">Cancel</button>
</div>
</div>
</div>
</div>
Inject $modal into your controller.
angular.module('app')
.controller('AlertModalController', function($scope,$modal ) {
//code
});
Now add this code into your controller.
In this code I am simply calling the template through the id which I have used the modal template. And two functions are called for cancel and leave through which the modal will get closed as per the function.
$scope.submit= function ( ) {
alertModalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: 'AlertpopupModal.html',
scope: $scope
});
$scope.leave = function () {
console.log("leave");
alertModalInstance.close(true);
};
$scope.cancel = function () {
console.log("cancel");
alertModalInstance.dismiss('cancel');
};
Try this:
export class AppComponent {
title = 'leave-site';
#HostListener('window:beforeunload', [ '$event' ]) beforeunloadHandler(event) {
return false;
}
}

Bootstrap3 confirm modal callback triggered twice

The code I used below works fine for first time.When I click cancel and press delete again ,function is called two times..In below example i get alert two times.I tried return false , still same problem.
Below is the javascript code
$(document).on("click",'.delbuttfultrackconfirm', function(e){
$('#delfultrackconfirm')
.modal({ backdrop: 'static', keyboard: false })
.one('click', '#delfultrackconfirmdel', function (e) {
alert("delete");
});
});
Hello below is the html code
<!-- Modal -->
<div class="modal fade" id="delfultrackconfirm" role="dialog" aria-labelledby="delfultrackconfirmLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div id="delfultrackconfirmbody" class="modal-body"> Are you sure want to delete this </div>
<div class="modal-footer"> <button type="button" data-dismiss="modal" class="btn btn-primary" id="delfultrackconfirmdel">Delete</button> <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> </div>
</div>
</div>
</div>
<br><br><br>
<center><button class="delbuttfultrackconfirm" href="#">del</button></center>
Here is bootply http://www.bootply.com/1Ghug4eX7p
Simply put the click function of the button outside the '. delbuttfultrackconfirm' click, like this
$(".delbuttfultrackconfirm").click(function(e){
$('#delfultrackconfirm').modal({ backdrop: 'static', keyboard: false });
});
$('#delfultrackconfirmdel').click(function (e) {
alert("delete");
});
The problem is your code is that every time you open the modal and not click on the "delete" button, you're adding another handler to be executed on the first click on the button.
Read the documentation: http://api.jquery.com/one/
This is because after each click you append event handler. This is happen because element store array of handlers, and after two clicks you have 2 handlers and each will be called.
function (e) {
alert("delete");
}
To avoid this just move handler to top;
$(".delbuttfultrackconfirm").click(function(e){
$('#delfultrackconfirm').modal({ backdrop: 'static', keyboard: false });
});
$('#delfultrackconfirmdel').click(function (e) {
alert("delete");
});
Demo

Categories