Set global instance of toastmessage using akquinet jquery toast message plugin - javascript

I was using jquery plugin to show toast message on the click of a button given a certain condition. But as and when I click on the button new toast message is shown. What I want to show is just one toast message being shown on the click of that button meaning, it should not show another toast message when my first toast message is still on the screen.
Is there some way to have global instance of it and then showing the same each time rather than show new one ?
Any help would be appreciated. Thanks in advance.

You could use a boolean to remember if the toast message is displayed. See jsfiddle (forked from the official demo). You could also use the myToast variable as "boolean" in a similar way.
$(document).ready(function() {
var isDisplaying = false;
var yourText = 'Success Dialog which is NOT sticky',
toastMessageSettings = {
text: yourText,
sticky: false,
position: 'top-right',
type: 'success',
closeText: '',
close: function() {
console.log("toast is closed ...");
isDisplaying = false;
}
};
$('#mybutton').click(function() {
if ( ! isDisplaying) {
var myToast = $().toastmessage('showToast', toastMessageSettings);
console.log('myToast:');
console.log(myToast);
isDisplaying = true;
}
});
});
<script src="http://akquinet.github.com/jquery-toastmessage-plugin/demo/jquery.toastmessage-min.js"></script>
<link href="http://akquinet.github.com/jquery-toastmessage-plugin/demo/css/jquery.toastmessage-min.css" rel="stylesheet"/>
<h1>jquery-toastmessage-plugin Demo
<br/><span class="small">by akquinet</span></h1>
<button id="mybutton">Press it</button>

Related

Bootstrap confirmation (remove click function ?)

I've just started to study bootstrap and I'd like to ask a question about it.
I'm using "bootstrap confirmation" referenced with URL below.
https://github.com/mistic100/Bootstrap-Confirmation/blob/master/example/index.html
I'm trying to use custom button of bootstrap confirmation
and i have a click function for this button as well.
but the problem is when i clicked the button it automatically show confirm box.
I wanted to show it when i call the function,
$("#button_id").confirmation("show");
as before I show confirm box i have to check the validation and get the result first...
Is there any way to do it? ..
ex)
$("#button_id").confirmation({
rootSelector: '',
container: 'body',
buttons: [
{
class: 'class',
value: 'YES',
label: 'YES',
onClick:function(){
}
}
]
});
HTML
<button id="bt1" class="btn btn-default" >Confirmation 1</button>
JS
$("#bt1").click(function() {
var test = prompt("test");
if( test == "test" )
{
$('#bt1').confirmation("show");
}
});
Hope this helps. :)
function validate() {
return true;
}
$('#id').click( function() {
var valid = validate();
if(valid) {
$('#id').modal('show');
}
});

Jquery dialog works only after the third click

There is a problem in my jquery dialog, since it is opened only after the third click. Can anyone help? Here is the snippet. When auto open is set true it works. But it creates another problem using auto open true. I dont know whats wrong with my code. In each click this particular function is called.
thanks.
function attachmentDialogBox(objId){
var parentDiv = objId;
if(parentDiv!=''){
var source = $("#"+parentDiv+" input[name=sourceId]").val();
var type = $("#"+parentDiv+" input[name=typeId]").val();
}
else{
var source = $("input[name=sourceId]").val();
var type = $("input[name=typeId]").val();
}
$.ajax({
url:"${createLink(controller: "fileAttachment",action: "rAttachmentDialog")}",
data:{id:"${id}",module:"${module}",moduleType:"${moduleType}",source:"${source}",sourceId:source,attachmentUrl:"${attachmentUrl}",multiple:"${multiple?:1}",type:type},
type:"post",
success:function(data){
$("#attachDocument").html(data);
$("#attachDocument").dialog({
title:"${module=="memberProfilePic"?"Upload Profile Image":"Attach Document"}",
zIndex:1103,
modal:true,
autoOpen:false,
width:"${module=="memberProfilePic"?355:"auto"}",
resizable:false,
draggable:false,
close:function(){
$("#attachDocument").remove();
$("#dialogContainer").append("<div id='attachDocument'></div>");
}
});
alert($("#attachDocument").val);
$("#attachDocument").dialog('open');
}
});
return false;
}
Try chaning it to this:
var dialog $("#attachDocument").dialog({...});
dialog.dialog("open");
I'm not entirely sure that $().dialog() returns the instance, but if it do, it should be a safer method
Changed to solution found through suggestions in comment.

Javascript redirect only seems to work when chrome debugger is open

I have written a Jquery-Ui Dialog to popup as a confirmation on particular links. This however does not redirect to my Delete page correctly. However if I open the debugger in chrome to debug, then the code works as expected.
I have found the same question, however the solution does not seem to work for me. It is exactly the same scenario though. Question here JavaScript redirect not working and works only in Chrome if debugger is turned on
So I have my link
<div id="confirm-dialog">
<div class="dialog-inner">
<p id="confirm-dialog-message"></p>
</div>
</div>
Delete
And I have my javascript
$('.confirmLink').click(function (e) {
BodyScrolling(false);
var theHref = $(this).attr("href");
var theTitle = $(this).attr("title") == null ? "Confirm..." : $(this).attr("title");
var theText = $(this).attr("data-confirm-message") == null ? "Are you sure?" : $(this).attr("data-confirm-message");
$("#confirm-dialog-message").html(theText);
$("#confirm-dialog").parent().css({ position: "fixed" }).end().dialog("open");
$("#confirm-dialog").dialog({
title: theTitle,
close: function() {
BodyScrolling(true);
},
buttons: [
{
text: "Yes",
class: "mws-button red",
click: function () {
$("#confirm-dialog").dialog("close");
window.location.href = theHref;
return false;
}
},
{
text: "No",
class: "mws-button black",
click: function () {
$("#confirm-dialog").dialog("close");
}
}]
});
return false;
});
So when I click my Delete link, I am indeed presented with my confirm dialog with Yes and No buttons, css styled correctly, and has captured the link href and bound it to the Yes button. If I click "No", I am kicked back and nothing further happens - Correct!
If I click Yes, it should take send me on to the original href that it captured. I have thrown alert(theHref) on the Yes Button click just before the redirect and it does show me the correct address (/Customer/Delete/73865878346587), but the redirect does not happen.
When I open the chrome debugger to debug the javascript or see if any errors occurred, then everything works as expected and redirects me correctly!
In IE, it does not work either.
I have tried...
window.location.href = theHref
window.location = theHref
location.href = theHref
$(location).attr('href', theHref)
I have also tried adding return false; after my redirect. Nothing works.
The link I added above to the same question said to make sure that the Yes button is being rendered on the page as a ... which mine is.
Can anyone shed any light?
Instead of window.location.href = theHref;
have you tried window.location.replace(theHref);?
Back to basics, try: window.location = theHref;
Well I have found the answer. Javascript was a red herring!
I did try to remove the confirmLink jQuery class so that the link was just a standard link that went straight to my controller to perofm my delete. When I did this test, the link worked perfectly. Therefore I denoted the problem be with my javascript. However, it seems that this was not quite the case and had only worked again if the Debugger in Chrome had been or was open at the time aswell.
When I revisited the non confirm link option again, I found this not to work properly, therefore denoting the problem not with the javascript.
It appears that you cannot perform a Delete action from a HTML Link in MVC. This is obviously because of security risks involved as anyone could perform a Delete on an Id. I had thought of this in my implementation and had added code to check where the Request had come from and if it wasn't from my List page, then it threw back an error and wouldn't perform the Delete. It didn't matter what I named my controller either, eg Test, the link performing my HTTP GET request would never hit this. There must be some algorithm that determines what the action is doing and stops you from performing the action on a HttpGet request. For more information about Delete Actions, check out this post http://stephenwalther.com/archive/2009/01/21/asp-net-mvc-tip-46-ndash-donrsquot-use-delete-links-because
It seems that you can only perform this by a HTTP Post, which means either using a Ajax.ActionLink or by using a Form and a submit button. Then your Action must be specified for HttpPost.
If, like me, you wish to keep your Link as a HTML Link, then you can do the following which is what I did, code below. I kept my HTML Link, set it up to point to my HttpPost Delete Action. Added my confirmLink class for jquery to bind my dialog box to. I pick up the link href and set the Yes button in the jquery dialog to dynamically create a Form and set the method to post and the action to the links href. Then I can call submit on the new dynamically created form to perform my Post to my Delete action.
My Delete Link
Html.ActionLink("Delete", "Delete", "Caterer", new { id = caterer.Id }, new { #class = "mws-ic-16 ic-delete imageButton confirmLink", #data_confirm_title = "Delete " + caterer.Name, #data_confirm_message = "Are you sure you want to delete this caterer, " + caterer.Name + "?" })
My Javascript
function LoadConfirm() {
$('.confirmLink').click(function (e) {
e.preventDefault();
BodyScrolling(false);
var actionHref = $(this).attr("href");
var confirmTitle = $(this).attr("data-confirm-title");
confirmTitle = confirmTitle == null ? "Confirm..." : confirmTitle;
var confirmMessage = $(this).attr("data-confirm-message");
confirmMessage = confirmMessage == null ? "Are you sure?" : confirmMessage;
$("#confirm-dialog").dialog({
autoOpen: false,
modal: true,
width: 400,
closeOnEscape: true,
close: function () { BodyScrolling(true); },
title: confirmTitle,
resizable: false,
buttons: [
{
text: "Yes",
class: "mws-button red",
click: function () {
StartLoading();
$(this).dialog("close");
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", actionHref);
form.submit();
}
},
{
text: "No",
class: "mws-button black",
click: function () {
$("#confirm-dialog").dialog("close");
return false;
}
}
]
});
$("#confirm-dialog #confirm-dialog-message").html(confirmMessage);
$("#confirm-dialog").parent().css({ position: "fixed" });
$("#confirm-dialog").dialog("open");
});
}
My Action
[HttpPost]
[Authorize(Roles = "User")]
public ActionResult Delete(long id)
{
//Perform my delete
return RedirectToActionPermanent("List");
}

Redefining a jQuery dialog button

In our application we use a general function to create jQuery dialogs which contain module-specific content. The custom dialog consists of 3 buttons (Cancel, Save, Apply). Apply does the same as Save but also closes the dialog.
Many modules are still using a custom post instead of an ajax-post. For this reason I'm looking to overwrite/redefine the buttons which are on a specific dialog.
So far I've got the buttons, but I'm unable to do something with them. Is it possible to get the buttons from a dialog (yes, I know) but apply a different function to them?
My code so far:
function OverrideDialogButtonCallbacks(sDialogInstance) {
oButtons = $( '#dialog' ).dialog( 'option', 'buttons' );
console.log(oButtons); // logs the buttons correctly
if(sDialogInstance == 'TestInstance') {
oButtons.Save = function() {
alert('A new callback has been assigned.');
// code for ajax-post will come here.
}
}
}
$('#dialog').dialog({
'buttons' : {
'Save' : {
id:"btn-save", // provide the id, if you want to apply a callback based on id selector
click: function() {
//
},
},
}
});
Did you try this? to override button's callback based on the need.
No need to re-assign at all. Try this.
function OverrideDialogButtonCallbacks(dialogSelector) {
var button = $(dialogSelector + " ~ .ui-dialog-buttonpane")
.find("button:contains('Save')");
button.unbind("click").on("click", function() {
alert("save overriden!");
});
}
Call it like OverrideDialogButtonCallbacks("#dialog");
Working fiddle: http://jsfiddle.net/codovations/yzfVT/
You can get the buttons using $(..).dialog('option', 'buttons'). This returns an array of objects that you can then rewire by searching through them and adjusting the click event:
// Rewire the callback for the first button
var buttons = $('#dialog').dialog('option', 'buttons');
buttons[0].click = function() { alert('Click rewired!'); };
See this fiddle for an example: http://jsfiddle.net/z4TTH/2/
If necessary, you can check the text of the button using button[i].text.
UPDATE:
The buttons option can be one of two forms, one is an array as described above, the other is an object where each property is the name of the button. To rewire the click event in this instance it's necessary to update the buttons option in the dialog:
// Rewire the callback for the OK button
var buttons = $('#dialog').dialog('option', 'buttons');
buttons.Ok = function() { alert('Click rewired!'); };
$('#dialog').dialog('option', 'buttons', buttons);
See this fiddle: http://jsfiddle.net/z4TTH/3/
Can you try binding your new function code with Click event of Save?
if(sDialogInstance == 'TestInstance') {
$('#'+savebtn_id).click(function() {
alert('A new callback has been assigned.');
// code for ajax-post will come here.
});
}

javascript Confirm replacement with return true/false

Since jquery UI dialog does not support returning true/false, I need some other way to replace a javascript confirm.
It has to return true/false, so that my validation processes in javascript will run:
var where_to_coupon = confirm(pm_info_msg_013);
if (where_to_coupon== true) {
doSubmit=true;
return doSubmit;
The only way I know of doing that is passing a callback to the function.
The problem you face is that JQuery UI will not block the execution like confirm to wait for user input so you need to open the dialog and when the user clicks an answer act accordingly.
If you use Jquery UI dialog you can bind the callback functions to the buttons.
For instance:
myConfirm("Are you sure?", function(){ [YES CODE] }, function(){ [NO CODE] });
Your custom confirm will look like this:
var myConfirm = function(msg, yesAction, noAction){
$.dialog{
[CODE],
buttons: {
yes: yeasAction,
no: noAction
}
};
};
jQuery UI can do what you want, you simply have to adjust your code to work in an async way. Ariel Popovosky gave an answer which attempts to wrap a dialog call into a simple function call, and would work well but would require the same basic sync/async code modifications that any change from window.confirm would require.
Using window.confirm we use a synchronous way of doing things--program halts while user makes a decision. See example: http://jsfiddle.net/9jY7E/
Using UI's dialog, we simply move the behavior which should happen on confirm into the behavior assigned to one of the UI buttons. The dialog shows, and the program continues to run. But because you moved your "ok" code into the functionality bound to the button, that code doesn't run until the user clicks it. The following link is the same example I showed with window.confirm, but has been modified to use UI dialog: http://jsfiddle.net/9jY7E/1/
I don't know of any replacement for window.confirm which works just like window.confirm but allows for your own styling. All dialog systems I know of work somewhat similar to UI.
Additional: At the following link you will find a 3rd example of the same external link confirmation using the methodology Ariel gave in his answer: http://jsfiddle.net/9jY7E/2/
This is a little convoluted, but it works for me. It sets a "global" variable and tests that value to see if the dialog should be displayed.
I know it probably isn't the most efficient method.
The confirmIt funciton returns true or false.
The reason for the setTimeout("confirmItConfirmed=false;",500); near the end is to reset the variable so the next time the function is called it won't just return true.
Some browsers do better at handling the auto height and width than others.
The notice function is a replacement for alert and confirmIt replaces confirm.
<html>
<head>
<title>jQuery Confirm & Alert Replacements</title>
<link type=text/css href=http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/redmond/jquery-ui.css rel=stylesheet />
<script type=text/javascript src=https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js></script>
<script type=text/javascript src=https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js></script>
<script type=text/javascript>
var confirmItConfirmed = false;
var jq = $.noConflict();
function notice(message,title,height,width) {
if (!title)
var title = document.title+' says...';
jq('body').append('<span id=noticeDialogSpan style=display:none></span>');
jq('#noticeDialogSpan').html('<div id=noticeDialog title="'+title+'">'+message+'</div>');
if (!width)
var width = jq('#noticeDialogSpan').width()+40;
if (!height)
if (jq('#noticeDialogSpan').height() > jq(window).height()-100)
var height = jq(window).height()-100;
else
var height = 'auto';
jq('#navMenu').hide();
jq('#noticeDialog').dialog ({
height: height,
width: width,
modal: true,
close: function(event,ui) {
jq(this).dialog('destroy');
jq('#noticeDialog').remove();
jq('#noticeDialogSpan').remove();
jq('#navMenu').show();
},
buttons: {
'Close': function() { jq(this).dialog('close'); }
}
});
}
function confirmIt(e,message,title,height,width) {
if (!confirmItConfirmed) {
if (!title)
var title = document.title+' says...';
jq('body').append('<span id=confirmationDialogSpan style=display:none></span>');
jq('#confirmationDialogSpan').html('<div id=confirmationDialog title="'+title+'">'+message+'</div>');
if (!width)
var width = jq('#confirmationDialogSpan').width()+40;
if (!height)
if (jq('#confirmationDialogSpan').height() > jq(window).height()-100)
var height = jq(window).height()-100;
else
var height = 'auto';
jq('#navMenu').hide();
jq('#confirmationDialog').dialog ({
height: height,
width: width,
modal: true,
close: function(event,ui) {
jq('#confirmationDialog').remove();
jq('#confirmationDialogSpan').remove();
jq(this).dialog('destroy');
jq('#navMenu').show();
},
buttons: {
'Confirm': function() {
jq(this).dialog('close');
confirmItConfirmed = true;
e.click();
},
'Cancel': function() { jq(this).dialog('close'); }
}
});
}
setTimeout("confirmItConfirmed=false;",500);
return confirmItConfirmed;
}
function testIt(e) {
if (confirmIt(e,'Are you sure you want to continue?','My Title'))
notice('You clicked Confirm','My Title');
}
</script>
</head>
<body>
<br />
<br />
Click HERE to test a link.
<br />
<br />
Click this button to test it too <input value='Click Me' type=button onclick="testIt(this)" />
</body>
</html>
This could also be done using boopup + callbacks:
Boopup.confirm("This is a boopup confirm!", function(agree) {
console.log(agree);
})
https://github.com/petruisfan/boopup

Categories