Create a confirmation alert for delete button in Angular using JS - javascript

I have a form that has a delete button, I would like to create a confirmation box that pop ups when the delete button is clicked. The delete button currently works. I have tried several things in javascript with no luck. I am using Angular.
Is this best approach for this?
Also, does anyone know of any examples for this, I have not found any that work.
$(document).ready(function(){
$("form").validate();
$(".radius small success button").ConfirmDialog('Are you sure?');
});

Seems like an AngularJS directive is a bit over-the-top for a solution to this. Seems easier just to use straight javascript unless you need some custom functionality to your "confirm()" function.
if (confirm('Are you sure you want to delete this?')) {
// TODO: Do something here if the answer is "Ok".
}
Hope this helps, cheers
UPDATE: Actually, with Angular, it would be better to use $window.confirm as this would allow you to test with Karma/Jasmine.

Here's another approach at this.
Basically it's a directive that gets the warning string you want to show, and the function to call if the user accepts. Usage example:
<button type="button" ng-really-message="Are you sure?"
ng-really-click="delete()">Delete</button>

This is how we're handling our 'confirmation dialogs' (using bootstrap)
The Markup
<div class="alert alert-block alert-error notification fade in" data-ng-show="displayLocationDeletePopup">
<h6>Are you sure you want to delete this location?</h6>
<div class="form-controls-alert">
No
Yes
</div>
</div><!-- end alert -->
Setting model to false on controller load to hide by default with ng-show
$scope.displayLocationDeletePopup = false;
On click on event for show popup, calls a function/passes model in
<i class="icon-remove" data-ng-click="showDeleteLocationPopup(true, location)"></i>
In the controller:
$scope.showDeleteLocationPopup = function(options, id) {
if (options === true) {
$scope.displayLocationDeletePopup = true;
} else {
$scope.displayLocationDeletePopup = false;
}
$scope.locationId = id;
};
And per the anchors in the html above, can either close the popup or run the function
$scope.deleteVendorLocation = function (storeLocation) {
// Code to run on confirmation
};

var r = confirm("Are you sure you want to Permanently delete this order?");
if (r == true) {
(OK button click) Write the function here.....
} else {
(Cancle button click) Write the function here.....
}

Place Delete option on the right hand side of each record and on clicking the delete option the record should get deleted from the details and JSON array.

Related

Sitecore 8 Speak UI - Call Pagecode Javascript from HTMLTemplate link

I am working on ListControl and one of the columns has Delete link which I am formatting using HTMLTemplate as follows:
<a href="javascript: app.showConfirmation()" >Delete</a>
My Javascript looks as follows:
define(["sitecore", function (Sitecore) {
var DestinationRules = Sitecore.Definitions.App.extend({
initialized: function () {
this.processDestinationRules();
},
showConfirmation: function () {
alert('here');
},
});
return DestinationRules;
});
For some reason, I am not able to call showConfirmation(). It says is undefined. I even tried Sitecore.Speak.app.showconfirmation() but not working.
I tried my best to search online but not able to find much help around calling function through controls embedded inside HTMLTemplate.
My next step is to call DialogWindow.
Please if you can help me with the syntax of the above. Thanks in advance.
Fixed it in a different way.
I wanted to show in-line Delete button in each row of the Listcontrol. Could not figure out way to call the
javascript: app.showConfirmation()
I changed the way to delete the record:
Have one Delete button outside the ListControl.
Enable/Disable the Delete button based on binding ListControl.HasSelectedItem.
On click of the Delete button, call showConfirmation()
As of now seems to be a better way. Sitecore itself uses similar approach for "Kicking off" users. Can be found here:
/sitecore/client/Applications/LicenseOptions/KickUser
Hope that helps. Thanks.
Finally, managed to do this. Always knew that it can be done this way but did not like the way its done.
The Delete link in List control opens up a confirmation Dialogue window. And if user selects Yes then it calls the app.onDeleteYes()
The HtmlMarkup for the column:
Delete
Added a button called btnDelete with visibility set to false.
Added following function, outside the scope of App:
var destinationRulePage = (function () {
var self = this;
self.showDeleteDialog = function (id) {
$("button[data-sc-id='btnYes']").attr("data-sc-click",
"javascript:app.onDeleteYes(" + id + ");");
$("button[data-sc-id='btnDelete']").click();
}
return self;
}())
This does the job for me. Thanks.

Re-usable popup solution in AngularJS

I am doing a project where there are about a dozen templates ( there will be more in future ) which i need to display in popup/modal dialog boxes. I've googled but i didnt quite like the solutions i saw (example) so i've decided to make my own.
I am working towards having an interface like this in my controller.
$scope.popup1Buttonclicked = function(){
dialogService.showdialog("popup1",$scope.popup1data,function(result,data){
if(result == "OK"){
//save data
}
});
};
And in my dialog service i am doing something like this:
myApp.service("dialogService",function($compile){
this.showdialog = function(popupid,data,callback){
var html = "<div>name: {{data.name}}</div>";
var element = $compile(html)(data);
$("#pop").append(element);
//$("#pop").showDialog(element);
};
});
I want two way binding on the popup so that after the dialog box is closed, i can pass the updated data to callback function.
Please check out plunker : http://plnkr.co/edit/uhZ0r0rXCacnvoyCP7nQ?p=preview
Can anyone point me in the right direction ?
After reviewing you code example:
$compile(html)(data);
data - should be $scope here.
have a look at this: http://plnkr.co/edit/SUQnUhX0wyi9UDMc4Vpl?p=preview
I created a directive to manage popups. This triggers the controller callback on close button click and passes data from the input box to it. From my understanding, this does roughly what you wanted to achieve.

making a custom Confirm box in javascript

I want to make a custom made confirmation box in javascipt just like the built in confirm box. the built in confirm box does not allow the code to progress unless the user selects atleast one thing. Below is my code:
*****HTML start*****
<div class = "popUp confirm" style="z-index:40000;" id="confirmBlock">
<div id = "confirmLabel" >Confirm Message</div>
<div style ="border:0px solid red;height:44.56px;">
<input id="Confirm" type="button" value="Confirm" onclick = "confirmAction(1)" />
<input id = "CancelConfirm" type="button" value="Cancel" onclick = "confirmAction(0)" />
</div>
</div>
*****HTML end*****
*****Javascript start*****
var confirmresult = "-1";
function confirmationLoop()
{
alert("If this alert is preesnt it works, seems like the built in alert provides some sort of pause for other parts of code to continue to work");
if(confirmresult == "-1")
confirmationLoop();
return;
}
function confirmAction(val)
{
confirmresult = val;
}
function checkuuu()
{
confirmresult = "1";
}
function confirmMessage(message)
{
document.getElementById("confirmLabel").innerHTML= message;
//var check = setTimeout(function(){confirmAction(1)},5000);
confirmationLoop();
/*
while(1) //using while almost does not allow any other part to run at all hence tried recursion
{
if(confirmresult != "-1")
break;
}
*/
document.getElementById("confirmLabel").innerHTML= "Confirm Message";
var returnVal = confirmresult;
confirmresult = -1;
return returnVal;
}
*****Javascript end*****
*****Sample code start*****
So this i what i expect below:
function example
{
var check = confirmMessage(message);
//the next part of code should not execute untill i press confirm or cancel, using settimeout or settimeinterval is asynchronous and the code flow continues. i want the effect something like alert and confirm built in boxes
}
*****Sample code end*****
I used loop but it keeps the thread completely occupied and does not give me a chance to press any button, which was quite obvious
However recursion gives u the freedom to perform other activities. The problem even though the value of confirmResult will become 1 upon pressing confirm button, which i check through alert. the recursive loop i.e. confirmation loop does not seem read it as 1. it still continues as -1. If i put a alert in that confirmation loop the value wil be read as 1. Can anyone help me to achieve what i started out to??????
P.s.=> sorry for such a huge question!!!
You can't use any sort of loop - as you've found it'll just cause the browser to lock up.
What you need to do is to emulate a "modal" dialog box.
This is usually done by having your dialog box appear on top of another "overlay" element which importantly covers every other element, and prevents any user interaction with them.
It's also pretty hard to implement a confirm function that'll return a value - the window.confirm method can only do that because it's synchronous - it blocks all other JS processing while the dialog is displayed.
The easiest approach is to instead supply a callback function that'll get called once the user has selected the desired value.

Return value from custom alert [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to create TRULY modal alerts/confirms in Javascript?
TL;DR: I've overridden the default alert() function with a custom HTML based one. I want the new dialogue to still block execution, and get the buttons within my dialogue to return true or false from the call to alert() to use in logic (and continue execution).
I'm trying to implement a custom alert box, which replaces the default browser alert with a nicely themed box with the same (or similar) functionality.
I've read this question, and I'm using the solution given in this answer (to the same question). What I want to do now is get my overridden alert to return a true or false value for use in if() statements, depending on whether OK or Cancel was clicked:
if(alert('Confirm?') {
// Do stuff
}
However, due to having custom HTML instead of a normal alert I can't do this for two reasons:
I can't return a value from the buttons in the replacement dialogue (click events bound with $.on()) because I have no idea how to.
I can't block program flow with this alert, as far as I know.
I've bound $.on() events to the Cancel and OK buttons in the replacement dialogue which hide the box. These work fine, but the problem I have now is returning a value when a button is clicked, so that execution will halt until an action is taken by the user.
HTML:
<div class="alert background"></div>
<div class="alert box">
<div class="message"></div>
<hr>
<div class="buttons">
<input type="button" name="cancel" value="Cancel">
<input type="button" name="confirm" value="OK">
</div>
</div>
Current JavaScript: (pretty much a carbon copy of the answer in my linked question)
(function () {
nalert = window.alert;
Type = {
native: 'native',
custom: 'custom'
};
})();
(function (proxy) {
proxy.alert = function () {
var message = (!arguments[0]) ? 'null' : arguments[0];
var type = (!arguments[1]) ? '' : arguments[1];
if (type && type == 'native') {
nalert(message);
} else {
// Custom alert box code
console.log(message);
}
};
})(this);
Ideally, I want to be able to put something like this in the // Custom alert box code part:
$('.alert.box input[name="confirm"]').on('click', function() {
// Hide dialogue box - I can do this already
// *** Return `true` or other truthy value from
// alert for use in `if()` statements
});
So that when the OK or Cancel button is clicked, it removes the custom alert box and returns a true or false value from the call to alert(). I can already remove the alert with $.fadeOut() and $.remove(), that's easy. What isn't is knowing how to get the button click events to get alert() (overridden) to return something.
I've tried to be as clear as I can, but I may have missed something out. Please let me know if I have.
The example below shows an approach to creating a custom alert and handling the outcome of the user selection
/*
message = String describing the alert
successCallBack = callback function for when the user selects yes
*/
function exampleAlert(message, successCallback)
{
/*Alert box object*/
var alertBox = document.createElement("div");
/*Alert message*/
var msg = document.createElement("div");
msg.innerHTML = message;
/*Yes and no buttons
The buttons in this example have been defined as div containers to accentuate the customisability expected by the thread starter*/
var btnYes = document.createElement("div");
btnYes.innerHTML= "Yes";
/*Both yes and no buttons should destroy the alert box by default, however the yes button will additionally call the successCallback function*/
btnYes.onclick = function(){ $(this.parentNode).remove();successCallback();}
var btnNo = document.createElement("div");
btnNo.innerHTML= "No"
btnNo.onclick = function(){ $(this.parentNode).remove();}
/*Append alert box to the current document body*/
$(alertBox).append(msg, btnYes, btnNo).appendTo("body");
}
function test()
{
alert("Example alert is working, don't use this test as a replacement test - horrible recursion!")
}
exampleAlert("shoe", test)
This is fairly basic and doesn't allow for additional data to be supplied to the callback function and for that reason is not ideal for production however jQuery's .bind() and similar methods allow for data to be associated with the callback method
It's worth commenting that while the above demonstrates a full implementation of the problem, there are in fact only two lines that actually matter.
btnYes.onclick...
btnNo.onclick...
Since we're achieving the desired result by binding onclick events for true and false respectively, everything else is there to paint the picture.
With that in mind it is possible to effectively turn any container object with at least one sibling into an alert box for eaxmple:
<!-- Example html -->
<div id='a'>
<ul>
<ul>
<li>Something</li>
<li>Something Else</li>
<li id='yesIdentifier'>Something not necessarily suggesting a trigger?</li>
</ul>
</ul>
</div>
As long as your yes / no (if no exists) options destroy the appropriate container a converting a container into an alert box can be handled in a couple of lines of code.
$('#yesIdentifier', '#a').click(
function(){ someCallback(); $(this).closest('#a').remove()});
Neither of the above are exemplary models for implementation but should provide some ideas on how to go about the task.
Finally... do you really need to replace the native alert method? That is, either you're writing the alert calls, in which case you'd know to use your custom method, or you're overwriting default behaviour that you can't guarantee the other developers will be aware of.
Overall recommendation:
I feel the best approach to this would be to create a jQuery plugin which creates the custom alerts on the fly and track callbacks, results and what not within the plugin.
SOliver.
Why don't you just use a confirm box like so.
var c = confirm('Confirm?');
if(c)
{
// Yes clicked
}
else
{
// No clicked
}
Or you could use jQuery UI's dialog confirmation box.
http://jqueryui.com/demos/dialog/#modal-confirmation

pausing execution in custom confirm box

I want to create a custom confirm box like this
var should_I_move_forward = myconfirmbox();
myconfirmbox will show a popup with Yes/No button, I want to pause the execution here until user hit yes or no, how can I achieve it?
i.e. same functionality as of js confirm method buy my own UI.
You can't.
You will have to move the logic that follows the confirmation inside the myconfirmbox method, or pass it as parameters (to call on demand)..
something like
function ConfirmYes(){
// do something for Yes
}
function ConfirmNo(){
// do something for No
}
function myconfirmbox(yesCallback, noCallback){
// whatever you currently do and at the end
if (confirmation == 'yes'){
yesCallback();
} else {
noCallback();
}
}
myconfirmbox(ConfirmYes, ConfirmNo);
What I did is not elegant at all but it working fine for me! I create a custom confirm function like:
function jqConf(msg,y,n){
$('body').append('<div id="confirmBox">msg</div>');
$('#confirmBox').append('<div id="confirmButtons"></div>');
$('#confirmButtons').append('<button onclick="'+y+'();">Yes</button>');
$('#confirmButtons').append('<button onclick="'+n+'();">No</button>');
}
function defaultYes(){
alert('Awesomeness!');
}
function defaultNo(){
alert('No action taken!');
}
The I use it like this:
<button onclick="jqConf('Do you love me?','defaultYes','defaultNo')">Confirm</button>
This way I pass as a string the name of the function to run if Yes and if No individually and is executed by the user event.
As I say, nothing elegant but it works!, no loops or confusing codes, I think?, In the example I'm using jQuery but can be accomplish with plain JavaScript too!

Categories

Resources