How can we create a confirmation alert in javascript with a save and discard button in it?
If we use the code
confirm('Do you want to save it?');
We will get an alert box with ok cancel.
How can we make the text of ok button as save and the other as discard?
You cannot modify the default javascript method "confirm". But, you can override it, for example, with jQuery UI dialog:
window.confirm = function (message) {
var html = "<div style='margin:20px;'><img style='float:left;margin-right:20px;' src='/img/confirm.gif' alt='Confirm'/><div style='display:table;height:1%;'>" + message + "</div></div>";
$(html).dialog({ closeOnEscape: false,
open: function (event, ui) { $('.ui-dialog-titlebar-close').hide(); },
modal: true,
resizable: false,
width: 400,
title: "Confirmation",
buttons: {
"Save": function () {
//Do what you need
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
}
this is not possible
more answers
Connect some of the tons JS framework. For example jQuery+UI
Overwrite window.confirm method, by makin it as wrapper to your favorite JS UI framework.
PROFIT!!!
Related
I have a LinkButton that executes on the server and changes the page. Historically, I've had a confirm message box that executes OnClientClick to ensure the user would like to navigate away.
So far it looks like this:
ASP.NET:
<asp:LinkButton runat="server" ID="ChangePage" Text="Change page"
OnClientClick="confirm('are you sure you want to change page?');"
OnClick="Navigate" >
Change Page
</asp:LinkButton>
HTML Output:
<a id="MainContent_ChangePage"
onclick="confirm('are you sure you want to change page?');"
href="javascript:__doPostBack('ctl00$MainContent$ChangePage','')" >
Change page
</a>
This all works fine like this. The trouble is that I'm trying to replace all confirm boxes with a prettier jQuery-UI implementation like this:
window.confirm = function (message, obj) {
$('<div/>')
.attr({ title: 'Webpage Confirm'})
.html(message)
.dialog({
resizable: false,
modal: true,
width: 500,
buttons: {
"OK": function () {
__doPostBack(obj, '');
$(this).dialog('close');
return true;
},
"Cancel": function () {
$(this).dialog('close');
return false;
}
}
});
};
I believe this has to do with the fact that the confirm dialog operates synchronously, while jQuery dialogs occur asynchronously. However, I thought setting modal: true would cause it to wait for a response.
How can I override window.confirm to get consistent behavior?
Add this to OK action:
var href = $(obj).attr("href");
window.location.replace(href);
window.navigator.location(href);
return true;
And remove __postback line
it works with me
I am trying to avoid the confirm box of javascript and tried that jquery.ui dialog box.
When confirm box returns true or false after that only remaining javascipt will execute,but in this jquery.ui dialog that not happening.
This what i tried,
I am having some of the links
function checkit(){
var istrue = showdial("confirm");
if(istrue== true) alert("yes");
else alert("no");
}
function showdial(tStr)
{
$('<div></div>').appendTo('body')
.html('<div><h4>Are you sure..?</h4></div>')
.dialog({
title: tStr,
zIndex: 10000,
autoOpen: true,
modal: true,
buttons:{
Yes: function(){
$(this).dialog("close");
return true;
}
No: function(){
$(this).dialog("close");
return false;
}
}
});
}
Please correct me if i did anything wrong above.
Before clicking that yes or no button it always alerts "no" only, . How can i run a script after that dialog returns an value. And i dont want that setTimeout() function to use.
Asynchronous code can't return values like that. Look at this related question which explains how to resolve this problem using callbacks.
I have a jQuery UI dialog that gets a line of text. If this text is not contained in a localStorage dictionary, I insert it into the dictionary. If it is present, I want to give the user the option not to overwrite the existing entry in the "ok" handler.
Because jQuery UI dialogs are stateful and persist across multiple calls unless explicitly removed (AFAICT), I'm not seeing a clear path to presenting the "are you sure you want to nuke your previous entry?" alert without resorting to ... uh ... alert.
The question, succinctly stated: Can you create a confirmation box from inside a jQuery UI Dialog?
Thanks.
I have not used jQuery UI Dialog, but you can always create your own html elements and do whatever you wish with them, including layering them on top of the jQuery dialog.
I guess you could have googled something to find these links:
Anyways have it and make fun:
JQuery Dialogs
Jquery Confirmation
Cheers!!!
Ok, it turned out the best way I found to handle this was using closures. Like this (pseudo-code):
getThingieName: handler(function() {
var $dialog;
$dialog = $('<div id="thingie-name-dialog" class="ui-widget"></div>').html("<p>Enter a name for this thingie</p>\n<input type=\"text\" id=\"dlg-thingie-name\" style=\"width: 80%\" />").dialog({
autoOpen: false
}, {
title: 'enter a name',
modal: true,
buttons: {
Add: function() {
var value = $('#dlg-thingie-name').val();
$(this).dialog('close');
$('#thingie-name-dialog').remove();
return handler(value); // <= closure to handle the onAdd
},
Cancel: function() {
$(this).dialog('close');
return $('#thingie-name-dialog').remove();
}
}
});
return $dialog.dialog('open');
}),
getConfirmation: function(message, handler) {
var $dialog;
$dialog = $('<div id="confirmation-dialog" class="ui-widget"></div>').html("<p>" + message + "</p>").dialog({
autoOpen: false
}, {
title: 'confirm overwrite',
modal: true,
buttons: {
Ok: function() {
$(this).dialog('close');
$('#confirmatio-dialog').remove();
return handler(true); // <= closure to handle onOk
},
Cancel: function() {
$(this).dialog('close');
$('#Thingie-name-dialog').remove();
return handler(false); // <= closure to handle onCancel
}
}
});
return $dialog.dialog('open');
}
// Calling sequence
Snippets.getSnippetName(function(value) {
if (value == null) return false;
if (localStorage.getItem(value)) {
getConfirmation("This thingie, " + value + ", already exists. Overwrite?", function(response) {
if (response) return localStorage.setItem(value, snippet);
});
} else {
localStorage.setItem(value, snippet);
}
}
This may not be the optimal code, but it does make the triggering of the dialogs dependent on the button push by embedding them in the handlers.
i want to open a model pop up on some button click in code behind which has got a few if else condition. First of all i am unable to fix what would be best approach.
What i options i think are followign.
1) calling a jquery model pop up
2) ajax model pop up
It is a button which fix on some button click condition to open the model pop up, if model pop says yes then, i want client to rediret to some payemnt page where he will pay to purchase the item.
Right now i am using the Jquery model pop up
which i am calling like this
protected void imgClientFreeEval_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
-----
---some code not typed
if (SurveyCount > 1)
{
Session["YourAssessment"] = true;
Session["MyAssessment"] = false;
ScriptManager.RegisterStartupScript(this, this.GetType(), "tmp", "<script>xyz()</script>", true);
//Response.Redirect("~/yourAssessment.aspx");
}
}
and i have model pop up like this
function xyz() {
// alert('hi tpo all');
// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
// $("#dialog:ui-dialog").dialog("destroy");
$(document).ready(function () {
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
autoOpen: false,
buttons: {
"OK": function () {
$(this).dialog("close");
window.location.replace("http://stackoverflow.com");
},
Cancel: function () {
window.location.replace("http://stackoverflow.com");
$(this).dialog("close");
}
}
});
});
}
Now the problem is that this function not getting called at all. what is wrong with this, i am toiling for long, if possible please suggest me best approach how should i execute it.
i am unable to call this javasccipt function from code behind button click.
The method I use to get javascript alerts up from my codebehind is like this:
public void AMessage(string message)
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "info only", "alert('" + message + "');", true);
}
If you aren't using the OnClientClick event in your button, then send the message through a similar handler. In your case, instead of calling "alert('" + message + "');" call the function you have written.
if you want to get alert and then redirect your page when OK is clicked. you can try like :
ClientScript.RegisterStartupScript(this.GetType(), "My alert", "alert('" Your time has been finished "');", true);
System.Text.StringBuilder sbs = new System.Text.StringBuilder();
sbs.Append("<script language='javascript'>");
sbs.Append("window.location = 'http://www.google.com/'");//or whatever you want:-
sbs.Append("</script>");
Type tr = this.GetType();
ClientScript.RegisterClientScriptBlock(tr, "PopupScript2", sbs.ToString());
Try using this :
function xyz() {
// alert('hi tpo all');
// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
// $("#dialog:ui-dialog").dialog("destroy");
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
autoOpen: false,
buttons: {
"OK": function () {
$(this).dialog("close");
window.location.replace("http://stackoverflow.com");
},
Cancel: function () {
window.location.replace("http://stackoverflow.com");
$(this).dialog("close");
}
}
});
});
}
One problem that I noted in your code is that in the line:
ScriptManager.RegisterStartupScript(this, this.GetType(), "tmp", "<script>xyz()</script>", true);
You are passing last parameter as true, which is addScriptTags, but you are already adding the script tag in the call, so might be it is creating problem over there.
Cheers
Firstly, I'm new at Javascript / Jquery so it might be a stupid question...
I'm using the dialog box that is in the JQuery UI collection. I have a button that when clicked, it either shows a confirm box or an alert box. My code is like below...
function checkfn() {
if (document.getElementById('<%=HomeInstSelected.ClientID%>').value == 'False') {
var dialogResult = false;
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
Continue: function () {
dialogResult = true;
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close").slideUp();
}
}
});
// alert just debug code!
alert(dialogResult);
return dialogResult;
}
else {
$("#dialog-HomeInstitutionPrompt").dialog({
height: 140,
modal: true
});
}
}
My problem is in the confirm part, it seems the confirm box is not waiting for me to hit Continue or Cancel - it's just going straight to the alert part and returning dialogResult = false.
Is it possible to halt execution of until after I've run the $('#dialog-confirm') command?
Alternatively, is it possible to return true for the checkfn() function, in the Continue function? That way, I will not need a dialogResult var at all?
I haven't used the .dialog in jQuery UI before, but, in general with jQuery, functions are run asynchronously. What this means is that you need to put the code that you want run in the Continue function.
One possibility is to send a success/cancel function to checkfn that you would call from the Continue and Cancel functions.
function checkfn(success, cancel) {
if (document.getElementById('<%=HomeInstSelected.ClientID%>').value == 'False') {
var dialogResult = false;
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
Continue: function () {
if(success) success();
$(this).dialog("close");
},
Cancel: function () {
if(cancel) cancel();
$(this).dialog("close").slideUp();
}
}
});
}
You can call the function like this:
checkfn(function () {
alert('success!');
}, function () {
alert('failure!');
});
Just put everything you want to do inside "Continue" and "Cancel" button definitions. So, you will not need a dialogResult and alert will hit when it is needed.
if (document.getElementById('<%=HomeInstSelected.ClientID%>').value == 'False') {
var dialogResult = false;
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
Continue: function () {
alert('Dialog result is true. I can do whatever I want here');
$(this).dialog("close");
},
Cancel: function () {
alert('Cancel is clicked. I should go on my life');
$(this).dialog("close").slideUp();
}
}
});
}
else {
$("#dialog-HomeInstitutionPrompt").dialog({
height: 140,
modal: true
});
}
-- You can't return a value for your function, because after initialization of the function, the code goes on. You need to fill Continue button definition.
This is something I struggled with when I started too, The code doesn't run as it reads on the page. When you call the dialog function it executes asynchronously. The continue and cancel functions are bound to the click actions on the buttons, meanwhile the code below the dialog function runs without waiting for the events.
Long story short the result needs to happen in the cancel and continue callbacks.
Problem is you're trying to return a boolean value when you should really pass the resulting functions in instead. Alot of things in jquery and javascript in general work that way. Thankfully the language provides the ability to program in this way.
function checkfn( resultfn(boolval) ) {
if (document.getElementById('<%=HomeInstSelected.ClientID%>').value == 'False') {
var dialogResult = false;
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
Continue: function () {
resultfn.call( this, true );
$(this).dialog("close");
},
Cancel: function () {
resultfn.call( this, false );
$(this).dialog("close").slideUp();
}
}
});
}
Put the if statement in "resultfn"
I had a similar frustrating problem where the jQuery dialog box would submit a form before the user had a chance to choose Yes or No.
Example HTML:
<form id="myForm" method="POST" action="/Where/To/Go">
<input type="submit" value="Submit" onclick="submitForm()"/>
</form>
And jQuery:
function submitForm() {
$('<div title="Submit Form>Are you sure you wish to submit the form?</div>').dialog({
modal: true,
buttons: [
{
text: "Yes",
click: function () {
$('#myForm').submit();
$(this).dialog("close");
}
}, {
text: "No",
click: function () {
$(this).dialog("close");
}
}
]
});
}
To fix the issue I changed the button from a submit type to a button type which stopped it submitting and triggering the jQuery dialog at the same time:
<input type="button" value="Submit" onclick="submitForm()"/>