I have a few different modals on a page, and it all works as it should, but if a user makes some input on form fields in a modal and then accidentally clicks outside of the modal (which closes it), they loose their changes, since if the user clicks the same button they pressed to open the modal, the data they entered will be overwritten with data pulled from the database.
So I'd like to have a function for "reopen last closed modal" that simply shows the modal again in it's last used state - with whatever data was in it.
Essentially like a Ctrl-Z for accidentally closing a modal.
It's really simple if you know the ID of the modal. Such as:
$('#myModal1').modal('show'); });
But because I have several different modals available on a page, and I don't want to have a bunch of "restore" buttons, I need to be able to detect the ID of the last closed modal.
If there's not a simpler way, I could capture the ID each time a modal is closed, and then use that ID if the modal needs to be reopened without changing its data. Something like this:
$('#myModal1').on('hidden.bs.modal', function (e) {
var LastModal = '#myModal1';
})
$('#myModal2').on('hidden.bs.modal', function (e) {
var LastModal = '#myModal2';
})
function reOpen() {
$(LastModal).modal('show');
}
But I'm guessing there's a way that's simpler and doesn't require me to state all my modals ID's in JS/jQuery. Any ideas?
I've made a few tweaks, and this is working well for me now, with essentially no other hassle than a few short lines of code in my script file.
var LastModal;
$('.modal').on('hidden.bs.modal', (e) => {LastModal = $(e.target).attr('id'); })
function reOpen() { $('#'+LastModal).modal('show');}
Just use the style class "modal" for your modals, and to call the "reOpen", just have something like:
<span onclick='reOpen();'>Reopen</span>
Thanks #marekful for your suggestion!
Also, if you want to access this (or any other function) by pressing Ctrl+Z, you can add this:
// press Ctrl+Z to restore modal
$(document).keydown(function(evt){
if (evt.keyCode==90 && (evt.ctrlKey)){
evt.preventDefault();
reOpen();
}
});
Related
I have a component Escrituracao to keep tab of a client's bills. It has this mat-table to show all the proper data. To create a new bill a modal, CadastrarLancamentoComponent, is opened:
openModalLancamento(data) {
const modalOptions: NgbModalOptions = {};
modalOptions.backdrop = 'static';
const modalRef = this.modalService.open(CadastrarLancamentoComponent, modalOptions);
modalRef.result.then((result) => {
if (result) {
this.getLancamentosByPeriod();
}
}, (result) => {
if (result) {
//escape result enters here
this.getLancamentosByPeriod();
}
});
}
When a new bill is added the modal is kept open to add more bills (that's intended). However, when closed with the close or cancel button, if a bill was added, the modal returns a specific result value enabling the page to refresh (thus calling this.getLancamentosByPeriod();). When using cancel or close button with no bill added, it only closes the modal without reloading.
My main struggle is when using the Escape key. When used, both when added or not a bill, it only closes the modal. The result is the same for both situations. I've tried using some Output data transfer to the Financeiro component to say a bill was added; and tried accessing the modal's data to fetch a boolean that would give me that information. All with no solution.
Is there a way to force a value on this modal result when closed with the escape key? Or to send this information proper (like used on the other close buttons) to the main page? What I need is the page to behave the same as the other closing buttons, to reload on close when a bill was added.
I'm using Angular/Typescript for this project.
Are you using material for your dialog, custom, or something else?
If it's material, then I believe there's and option to disable escape being used to close it.
Yeah, looked it up, disableClose is the option. That removes escape and clicking outside of the dialog as ways to close it.
Once disabled, put your own escape key listener in there - something like this I guess - and when escape is detected, directly call your desired, custom close method.
I have a table (formatted with Datatables script) and it has a column which contain few icons to manage actions. When user click on an icon, it load a modal and get the modal content using POST method.
Modal has a save button to complete the action after user make their choice. When they click save button, another post script complete the request and feedback to user.
This process working fine when the first time user load the page. There is a refresh button on the page which can reload the TABLE without reload the PAGE.
If user use this button to refresh the page and try above action. it open the modal and Save button trigger the post action 2 times. If the user refresh the page (using the refresh button) again and try one of the action icons, post script run 3 times... in other words if you refresh 10 times post script run 10 times...
if user use the browser refresh button, we don't get this repetition.
Just wondering whether we can fix this without get rid of the refresh button.
We tried different ways to place the script within the page. but still cannot understand what is triggering the multiple post request.
//javascript
//step 1 - load the modal with an action list
$("#proj_data tbody").on("click", ".update_job_progress", function () {
var pn = $(this).attr('mypn');
$.post('reports_job_progress.php', {proj: pn}, function (data) {
$('<div id="progress_update_modal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true"></div>').appendTo('#modal-container').html(data).modal();
});
});
//step 2 - save user choice
$('body #modal-container').on('click', '.btn_jobaction', function () {
var pn = $("#pn").val();
$.post("reports_job_progress_backend.php", $("#progress_list").serialize(),
function (res) {
if (res === 0) {
alert("There is a problem saving the information. please try again");
} else {
$("#prog" + pn).html(res);
$("#progress_update_modal").modal('hide');
}
}
);
});
//step 3 - destroy the modal
$("body").on("hidden.bs.modal", ".modal", function () {
$("#modal-container").empty();
});
Could you please help me to understand the issue with this code?
It looks like your problem is being caused by binding multiple onclick handlers to the element. Please try using off like this $("#proj_data tbody").off("click").on("click", ... and see if that fixes your issue.
#buffy solution worked. However just adding .off('click') was disabling other icons click event as all icons share the same class. after playing with the code i found adding $(this).off('click') does the trick. Now everything working perfect. Thanks #buffy for providing correct directions.
You will bind the click event multiple times. You could either reset the callback, check if the callback has been set or (much better) set the click listener in a part of your script, that will not be executed, whenever you refresh your page (with the mentioned refresh button) like:
$(document).ready(function() {
$('body #modal-container').on('click', ...
$('body #modal-container').on('click', ...
});
I am using feather-light modal in my page. on the modal one form is there with certain input fields. Once I fill in the fields and close the modal and when I open it again , it contains the previously filled data. I want to clear the data once it is closed. I am using angular js in my page.
Can anyone tell me how can I clear the feather-light modal using angular js?
Update-
In my code I have to open another modal after closing the first modal. And once second modal closes, if I am opening my first modal, its showing the previously filled data, I want to reset the modal data of first modal.
in my html I am using below code-
<button type="submit" ng-click="anotherModal(myForm)" ng-class="{ 'featherlight-close' : myForm.$valid}">Submit</button>
and in script I am using below code-
$scope.anotherModal= function (myForm) {
if ($scope.myForm.$valid) {
$scope.myForm.$submitted = true;
$.featherlight("#f12","open");
}
}
Can anyone tell me where should I add to reset the first modal?
Updated Plunker-
Please find my plunker here-
https://plnkr.co/edit/cDP1eqtUsKkeMaUiCIoM?p=preview
I am using persist ='shared' in my code because if I remove this then form validation won't work on first modal.
My issue is that when I open my second modal next time,it contains previously filled values and from there when I click on submit button my second modal doesn't show up.
Can anyone help me in solving my issue?
If you are using the persist option, then yeah, the form is persisted, so you'll have to clear it yourself.
If not, then you'll get a new copied form each time. In that case though, you'll have to be careful about how you bind it and avoid using any IDs, since those are supposed to be unique.
As far as I know featherlight is gallery plugin, used for displaying images in a lightbox. Considering this it is not meant to be used like that (even though you can, but it will not behave as you expect here out of the box), so that's why you'll have to cleanup behind you (or more specific your users), and on popup close action, clear all form fields. There are several ways to do that, eg. form reset button (input type="reset"), js callback on close popup or submit event (or in your case using angular js events), etc..
Since you didn't provide any code that's all I can tell you for now..
Also possible duplicate of Resetting form after submit in Angularjs
UPDATE
Not sure what exactly are you trying to achive here, but if you remove (or move inside showAnotherModal function) $.featherlight.defaults.persist=true; line, it works as you described, first popup is cleared when you open it for second time. Here is your snippet updated:
var app = angular.module('myApp', ['ngMessages']);
app.controller('myCtrl', function($scope) {
// $.featherlight.defaults.persist="shared";
$scope.showAnotherModal = function () {
$.featherlight.defaults.persist="shared";
if ($scope.myForm.$valid) {
$scope.myForm.$submitted = true;
$scope.myForm.dirty = false;
$scope.myForm.$setPristine();
$scope.myForm.$setUntouched();
$.featherlight("#fl3",'open');
}
}
});
The scenario I'm trying to solve is to disable that the escape-button closes the dialog AFTER the modal has been instaniated (the dialog is set to a loading state). So in other words after I have instaniated my modal like this:
(this.$el).modal("show");
The user presses a submit button and the dialog is set to a loading state and I want to disable the escape-button since the user should not be able to close the dialog in this state.
I have tried this:
(this.$el).modal({ keyboard: false });
But it does not work, it seems that Bootstrap only reads those options when it instaniates the modal dialog...
So my question is if it is possible to get a hold of the actual bootstrap modal-instance to be able to change the options-object? According to the documentation it should be possible (or have I misunderstood the docs?), but I cannot figure out how.
Here is what it says in the documentation (http://getbootstrap.com/javascript/):
If you'd like to get a particular plugin instance, retrieve it directly from an element:
$('[rel="popover"]').data('popover').
Any ideas?
Ok, I figured out how to get ahold of the modal dialog instance after some experimentation:
var bootstrapModalInstance = this.$el.data("bs.modal");
And then I could set the options on the instance like this:
bootstrapModalInstance.options.keyboard = !this.model.isSyncing;
Sadly enough, this did not solve the problem since the escape-key-event-listener is setup during the modal instaniation like this:
From bootstrap.js
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) { // The event listener is setup on initalization
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide() // !!! Does not check the instance options.keyboard flag status, so I had to add && this.options.keyboard here
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
And as I wrote in the code comment above adding the instance options.keyboard check in the event listener solved the issue.
I have a problem. I have a registry form and many other forms.
Now I want to check whether the form is dirty and then I bring a confirm box if they really want to leave/close this page.
First of all, when I go back with the browser's back button and not with my other button ([button..] just 4 example) the confirmation box shows up two times and after two times confirming I'm still on the same page, just the form is resetted. When I press my own everything works fine.
Secondly, when I close the browser, my confirmation box shows up and afterwards the browsers confirmation box also shows up, but I only want one of them.
$scope.$on('$locationChangeStart', function (event, next, current) {
if ($scope.requestForm.$dirty) {
if (!$window.confirm('Unsaved Changes, leave Page?')) {
//cancel leaving view2
//works when clicking links, but doesn't work when using the back button
event.preventDefault();
}
} else {
}
});
$scope.$watch("requestForm.$dirty", function (newval) {
window.myGlobalDirtyFlag = newval;
});
window.onbeforeunload = function (e) {
if (window.myGlobalDirtyFlag === true) {
if (!$window.confirm('Unsaved Changes, close Page?')) {
//cancel leaving view2
//works when clicking links, but doesn't work when using the back button
return false;
} else {
}
}
};
$scope.$on("$destroy", function () {
window.myGlobalDirtyFlag = false;
});
May someone also have an idea how I bring this into an AngularJS directive, so I don't have to copy this code for every site where I have a form on it. (Every page only has 1 form, but every form name is different!)
My controllers are in seperate javascript files, (function blablaController() {}) and I pass this per routeProvider in my config file (templateUrl: blabla.html, controller: blabalController)
Regards,
Anthrax
Here is a service and directive that answers your question. Probably the only change you might consider making to it is using $window instead of window inside the service. As the instructions state, you'll just add the attribute unsaved-changes-warning to your form.
https://github.com/facultymatt/angular-unsavedChanges