Add an OK and Cancel Button in javascript - c#

$(document).ready(function () {
$('.abc').click(function () {
var status = $("#<%=ddlstatus.ClientID%>").val;
if (status == "Prepared") {
var _Action = confirm('Do you really want to cancel this payment ? All pending money will be available in the retention account of the contractor ');
if (_Action) {
$.blockUI({ css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: .5,
color: '#fff'
}
});
return true;
}
else {
return false;
}
}
});
});
I get the OK button when I run this javascript but I want to add a cancel button as well. Plus i am calling this from c# code behind

You can try using jQuery UI Dialog:
<div id="dialog" title="Confirmation Required">
Do you really want to cancel this payment? All pending money will be available in the retention account of the contractor.
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#dialog").dialog({
autoOpen: false,
modal: true
});
});
$(".abc").click(function(e) {
e.preventDefault();
var targetUrl = $(this).attr("href");
var status = $("#<%=ddlstatus.ClientID%>").val();
$("#dialog").dialog({
buttons : {
"Ok" : function() {
if (status == "Prepared") {
$.blockUI({ css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: .5,
color: '#fff'
}
});
}
window.location.href = targetUrl;
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
$("#dialog").dialog("open");
});
</script>
DEMO: http://jsfiddle.net/rCVrc/
EDIT:
Quoting Nick's answer here, you can use the ScriptManager.RegisterStartupScript() method, like this:
ScriptManager.RegisterStartupScript(this, GetType(), "modalscript",
"$(function() { $('#dialog').dialog({
buttons : {
'Ok' : function() {
if (status == 'Prepared') {
$.blockUI({ css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: .5,
color: '#fff'
}
});
}
window.location.href = targetUrl;
},
'Cancel' : function() {
$(this).dialog('close');
}
}
}); });", true);
"If you're not using a ScriptManager/UpdatePanels, use the equivalent ClientScriptManager version.
It's important to remember to wrap your code in a document.ready handler (IE has the most issues without it), so your elements (in my example, id="dialog") are in the DOM and ready."

This is a long shot, but does using window.confirm() give any improvement over confirm() ?

confirm() should do the trick. Check this link. http://www.w3schools.com/js/tryit.asp?filename=tryjs_confirm

Related

Asp:Button - if OnClientClick = True | False

<asp:Button ID="Invoice" runat="server" Text="Create Invoice" OnClientClick="CreateInvoice_Click()" OnClick="CreateInvoice_Click1"/>
<script type="text/javascript" language="javascript">
function Create_Invoice() {
$("#dialog-confirm").dialog({
resizable: false,
height: 180,
modal: true,
buttons: {
Create: function () {
$(this).dialog("close");
},
Cancel: function () {
//code needed here
$(this).dialog("close");
}
}
});
}
</script>
<p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>Are you sure?</p>
So user presses the 'Create Invoice' button, pop up appears allowing the user to select 'Create' or 'Cancel'.
The 'CreateInvoice_Click' function is run on code behind if the user clicks 'create' or 'cancel'. What I want to know (which needs to go inside the 'cancel' function') how do I say ignore the OnClick="CreateInvoice_Click1" if cancelled is clicked.?
Thanks for any replies
if you want to prevent the server side function from execution you simply need to return false in your client side function.
function Create_Invoice() {
$("#dialog-confirm").dialog({
resizable: false,
height: 180,
modal: true,
buttons: {
Create: function () {
$(this).dialog("close");
},
Cancel: function () {
//code needed here
$(this).dialog("close");
return false;// that's all what you need
}
}
});
}
Seems like you are tryign to recreate something javascript does with a built in function.
function confirmation() {
var answer = confirm("Leave tizag.com?")
if (answer){
alert("Bye bye!")
window.location = "http://www.google.com/";
}
else{
alert("Thanks for sticking around!")
}
}
Taken from http://www.tizag.com/javascriptT/javascriptconfirm.php
you should try manually calling the serverside click event by using javascript;
checkout the code inside Create and Cancel button;
<script type="text/javascript">
$('#test').on('click', function(e){
e.preventDefault();
$("#dialog-confirm").dialog({
resizable: false,
height: 180,
modal: true,
buttons: {
Create: function () {
$(this).dialog("close");
// manually calling serverside click event
$('#buttonHidden').click();
},
Cancel: function () {
//code needed here
$(this).dialog("close");
// don't call it manually here and thus it won't fire the serverside click event
}
}
});
});
</script>
// your button here to call javascript
<button id="test" runat="server">Create Invoice</button>
// the hidden button just to hold the CreateInvoice_Click1 which is fired from fireClick()
<asp:Button ID="buttonHidden" runat="server" Style="display: none" OnClick="CreateInvoice_Click1" />
your code behind;
protected void CreateInvoice_Click1(Object sender, EventArgs e)
{
//your server side code
}
<asp:Button ID="Invoice" runat="server" Text="Create Invoice" OnClientClick="return Create_Invoice()" OnClick="CreateInvoice_Click1"/>
<script type="text/javascript" language="javascript">
function Create_Invoice() {
$("#dialog-confirm").dialog({
resizable: false,
height: 180,
modal: true,
buttons: {
Create: function () {
$(this).dialog("close");
return true;
},
Cancel: function () {
//code needed here
$(this).dialog("close");
return false;
}
}
});
}
<p id="dialog-confirm"><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>Are you sure?</p>
your code behind;
protected void CreateInvoice_Click1(Object sender, EventArgs e)
{
//your server side code
}

JQuery Dialog text area disappears on clicking on any other input

I am developing .NET MVC3 application in which I am using jquery dialog to display some text msg and text area together in pop up with OK Cancel button which is in a div "divForSentToCaseCommentLable". I am calling this dialog on button click "sentToCase".
chtml
<div id="divForSentToCaseComment">
<div id="divForSentToCaseCommentLable" style="display: none">
<b>
#Html.Raw("You are about to send the Alert to the Case Management queue and will be unable to make any further edits.")
<br />
#Html.Raw("Would you like to continue?")
</b>
<br />
#Html.Raw("Reason for status change:")
<br />
</div>
<div id="divShowCommentForStatusNDuedateChange" style="display: none">
#Html.TextArea("StatusDueDateChangeComment", new { #id = "StatusDueDateChangeComment", #name = "StatusDueDateChangeComment", String.Empty, #class = "text-box multi-line", #maxlength = "8000", #onkeypress = "return ImposeMaxLength(this,8000)", #onpaste = "return MaxLengthPaste(this,8000)" })
<div id="StatusCommentValidateMessage" style="display: none" />
</div>
</div>
JQuery
$("#sentToCase").click(function () {
if (isChanged && !isSubmit) {
var conf = confirm("The changes you made have not been saved. \nWould you like to continue?");
if (!conf) {
return false;
}
}
window.onbeforeunload = null;
$("#StatusDueDateChangeComment").val('');
$("#StatusCommentValidateMessage").hide();
$("#divShowCommentForStatusNDuedateChange").show();
$("#divForSentToCaseCommentLable").show();
$('#divForSentToCaseComment').dialog({
autoOpen: false,
resizable: true,
width: 415,
height: 300,
modal: true,
fontsize: 10,
title: 'Reason for send to case',
buttons: {
"Ok": function () {
// var sendToCaseAnswer = confirm("You are about to send the Alert to Cases and will be unable to make any further edits. Would you like to continue?");
// if (sendToCaseAnswer) {
var reasonForClear = $("#StatusDueDateChangeComment").val();
var incidentId = $("#IncidentID").val();
if (validateSatusComment(reasonForClear, "SentToCase")) {
$.blockUI({ message: '<h2><img src="../../Content/images/spinner.gif" />Loading ...</h2>' });
$.ajax({
type: "GET",
data: { incidentId: incidentId, reasonForClear: reasonForClear },
//url: '/Bamplus/AlertAndCaseManager/Alert/SendToCaseStatus',
url: sendToCaseStatusJsonUrl,
dataType: "json",
cache: false,
contentType: "application/json",
success: function (data) {
if (data.redirectTo != null) {
window.location = data.redirectTo;
$.unblockUI({ fadeOut: 200 });
} else {
$('#Messages').show(400);
$("#Messages").html(data.Html);
$.unblockUI({ fadeOut: 200 });
}
},
error: function () {
$.unblockUI({ fadeOut: 200 });
}
});
// }
$(this).dialog("close");
}
},
Cancel: function () {
$(this).dialog("close");
}
}, open: function () {
$('.ui-dialog-buttonpane').find('button:contains("Cancel")').removeClass().addClass("Button");
$('.ui-dialog-buttonpane').find('button:contains("Ok")').removeClass().addClass("Button");
}
});
$("#divForSentToCaseComment").dialog("open");
return false;
});
There is another button "watching" which is calling "divShowCommentForStatusNDuedateChange" div in dialog box to display only text area with Ok Cancel button
JQuery:
$("#watching").click(function () {
if (isChanged && !isSubmit) {
var conf = confirm("The changes you made have not been saved. \nWould you like to continue?");
if (!conf) {
return false;
}
}
window.onbeforeunload = null;
$('#divShowCommentForStatusNDuedateChange').dialog({
autoOpen: false,
resizable: false,
width: 350,
height: 220,
modal: true,
fontsize: 10,
title: 'Reason for status change',
buttons: {
"Ok": function () {
var reasonForClear = $("#StatusDueDateChangeComment").val();
var incidentId = $("#IncidentID").val();
if (validateSatusComment(reasonForClear, "Watching")) {
$.blockUI({ message: '<h2><img src="../../Content/images/spinner.gif" />Loading ...</h2>' });
$.ajax({
type: "GET",
data: { incidentId: incidentId, reasonForClear: reasonForClear },
//url: '/Bamplus/AlertAndCaseManager/Alert/WatchingStatus',
url: watchingStatusJsonUrl,
dataType: "json",
cache: false,
contentType: "application/json",
success: function (result) {
if (result.redirectTo != null) {
window.location = result.redirectTo;
$.unblockUI({ fadeOut: 200 });
} else {
$('#Messages').show(400);
$("#Messages").html(result.Html);
$.unblockUI({ fadeOut: 200 });
}
},
error: function () {
$.unblockUI({ fadeOut: 200 });
}
});
$(this).dialog("close");
}
},
Cancel: function () {
$(this).dialog("close");
}
},
open: function () {
$('.ui-dialog-buttonpane').find('button:contains("Cancel")').removeClass().addClass("Button");
$('.ui-dialog-buttonpane').find('button:contains("Ok")').removeClass().addClass("Button");
}
});
$("#StatusDueDateChangeComment").val('');
$("#StatusCommentValidateMessage").hide();
$("#divShowCommentForStatusNDuedateChange").dialog("open");
return false;
});
Problem-
scenario 1:
on page load I click on "watching" button to display "watching pop-up" with only
text area and "OK Cancel button", which is perfect.
Then I press "Cancel button" from "watching pop-up" which will hide "watching pop-up"
Now I go for "sentToCase" button from main page to display "sentToCase pop-up" with text message and text area.
I found that text area is not rendering in "sentToCase pop-up", I can only see text message in "sentToCase pop-up".
scenario 2:
On first page load if I directly click on "sentToCase" button then, "sentToCase pop-up" correctly renders text message and text area with "OK cancel button" which is correct.
I found solution for this problem by referring this post
jquery ui dialog box removes <div> after closing
The problem here is that you have your dialogs nested. The way jQuery dialog works is that it assumes all dialogs must be exclusive. Do not nest your dialogs, and you should be ok.
after separating div's existing code works fine. I done it like this
<div id="divForSentToCaseComment">
<div id="divForSentToCaseCommentLable" style="display: none">
<b>
#Html.Raw("You are about to send the Alert to the Case Management queue and will be unable to make any further edits.")
<br />
#Html.Raw("Would you like to continue?")
</b>
<br />
#Html.Raw("Reason for status change:")
<br />
</div>
<div id="divShowCommentForStatusNDuedateChangeSendToCase" style="display: none">
#Html.TextArea("StatusDueDateChangeComment", new { #id = "StatusDueDateChangeCommentSendTocase", #name = "StatusDueDateChangeComment", String.Empty, #class = "text-box multi-line", #maxlength = "8000", #onkeypress = "return ImposeMaxLength(this,8000)", #onpaste = "return MaxLengthPaste(this,8000)" })
<div id="StatusCommentValidateMessageSendToCase" style="display: none" />
</div>
</div>
<div id="divShowCommentForStatusNDuedateChange" style="display: none">
#Html.TextArea("StatusDueDateChangeComment", new { #id = "StatusDueDateChangeComment", #name = "StatusDueDateChangeComment", String.Empty, #class = "text-box multi-line", #maxlength = "8000", #onkeypress = "return ImposeMaxLength(this,8000)", #onpaste = "return MaxLengthPaste(this,8000)" })
<div id="StatusCommentValidateMessage" style="display: none" />
</div>
but because of separate divs I need to do some extra efforts on validation an all.
Thank you

How to refresh a parent page after closing sharepoint dialog?

How to refresh a parent page after closing sharepoint dialog?
Here is my coding to open a pop-up.
<input type="button" value="Add" class="button submit" style="width: 80px" onclick="javascript:OpenAttachmentUpload()" />
<script type="text/javascript">
//User Defined Function to Open Dialog Framework
function OpenAttachmentUpload() {
var strPageURL = '<%= ResolveClientUrl("~/Dialogs/AttachUpload.aspx") %>';
//OpenFixCustomDialog(strPageURL, "Attachment");
OpenCustomDialog(strPageURL, 350, 200, "Attachment");
return false;
}
</script>
here is the script.
function OpenCustomDialog(dialogUrl, dialogWidth, dialogHeight, dialogTitle, dialogAllowMaximize, dialogShowClose) {
var options = {
url: dialogUrl,
allowMaximize: dialogAllowMaximize,
showClose: dialogShowClose,
width: dialogWidth,
height: dialogHeight,
title: dialogTitle,
dialogReturnValueCallback: Function.createDelegate(null, CloseCallback3)
};
SP.UI.ModalDialog.showModalDialog(options);
}
After opening it, when I close the pop-up (~/Dialogs/AttachUpload.aspx) , I wanna refresh the parent page.
How can I do it?
I google and see SP.UI.ModalDialog.RefreshPage but still can't find an answer for me.
Thanks.
P.s
I don't know much about SharePoint.
You're almost there.
In the option dialogReturnValueCallback you can define a function that will be executed after the dialog was closed. By now you create a delegate pointing to CloseCallback3 but this is not defined in your code.
If you call SP.UI.ModalDialog.RefreshPage in this callback method the page gets refreshed after the dialog was closed with OK.
var options =
{
url: dialogUrl,
allowMaximize: dialogAllowMaximize,
showClose: dialogShowClose,
width: dialogWidth,
height: dialogHeight,
title: dialogTitle,
dialogReturnValueCallback: function(dialogResult)
{
SP.UI.ModalDialog.RefreshPage(dialogResult)
}
}
Btw:
You use javascript: in the onclick of the button. This is not necessary. this is only required in the href of an a tag
You can also use the build-in function "RefreshOnDialogClose"
SP.UI.ModalDialog.showModalDialog({
url: dialogUrl,
allowMaximize: dialogAllowMaximize,
showClose: dialogShowClose,
width: dialogWidth,
height: dialogHeight,
title: dialogTitle,
dialogReturnValueCallback: RefreshOnDialogClose
});
Try to use this code on click of a button:
<script type="text/javascript">
function RefreshParent()
{
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.Ok, null);
}
</script>
If you only want to refresh the page if changes were made you can use the following call back instead.
var options =
{
url: dialogUrl,
allowMaximize: dialogAllowMaximize,
showClose: dialogShowClose,
width: dialogWidth,
height: dialogHeight,
title: dialogTitle,
dialogReturnValueCallback: function(dialogResult)
{
if (dialogResult != SP.UI.DialogResult.cancel)
{
SP.UI.ModalDialog.RefreshPage(dialogResult)
}
}
}
Saves you from refreshing the page if the user hit cancel.
Try java-script code as below in Closecall back.
window.location = window.location;

Literal control not updating

I am using a plugin called uploadify to show file upload progress to users. The uploadify script calls default.aspx (asynchronously). In the Page_Load method of the default.aspx I run validation checks on the other form data that was passed through it.
If a validation check fails I like to display an error message using a literal control and then exit. The problem is the literal control is not being updated with the validation error messages.
Updated
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
if (context.Request.Files["Filedata"] != null)
{
if (context.Request["Name"] == null)
{
litValidationErrors.InnerHtml = "Please enter a name";
return;
}
}
}
}
<script type="text/javascript">
$(document).ready(function ()
{
$('#file_upload').uploadify({
'uploader': '/Plugins/Uploadify/uploadify.swf',
'script': '/default.aspx',
'cancelImg': '/Plugins/Uploadify/images/cancel.png',
'folder': '/FileUploads',
'auto': false,
'onComplete': function (event, ID, fileObj, response, data)
{
var uploadifyResponse = $("#<%= litValidationErrors.ClientID %>", $(response));
if (uploadifyResponse.length > 0)
{
$("#<%= litValidationErrors.ClientID %>").css("display", "inline").text(uploadifyResponse.text());
}
}
});
$('#MainContent_superSubmit').click(function ()
{
var jsonFormData = {
'Name': $('#MainContent_txtName').val(),
'Password': $('#MainContent_txtPassword').val()
};
$('#file_upload').uploadifySettings('scriptData', jsonFormData);
$('#file_upload').uploadifyUpload();
});
});
</script>
<html>
.....
<asp:Button ID="superSubmit" runat="server" Text="Button" />
<span id="litValidationErrors" runat="server" style="display: none; color: #ff0000;"></span>
</html>
Change the litValidationErrors control from Literal to the span with runat="server", remove Visible="false" and hide it by setting style="display: none;". Also, add the onComplete event handler to the uploadify:
$(function () {
$('#file_upload').uploadify({
'uploader': '/Plugins/Uploadify/uploadify.swf',
'script': '/WebForm1.aspx',
'expressInstall': '/Plugins/UploadifyexpressInstall.swf',
'cancelImg': '/Plugins/Uploadify/images/cancel.png',
'folder': '/App_Data/FileUploads',
'auto': false,
'onComplete': function (event, ID, fileObj, response, data) {
var uploadifyResponse = $("#<%= litValidationErrors.ClientID %>", $(response));
if (uploadifyResponse.length > 0) {
$("#<%= litValidationErrors.ClientID %>").css("display", "inline").text(uploadifyResponse.text());
}
}
});
});
Add callback function to your script that will update the text of literal control

call blockUI on button onclick

I'm trying to call an blockUI after a buttonclick, but I can't get it to work.
What am I doing wrong?
Script:
$(function() {
$('#<%= btnSave.ClientID %>').click(function(e) {
e.preventDefault();
$.blockUI({
message: '<div><h1><img src="Images/busy.gif" /> Please wait...</h1>',
css: { textAlign: 'center', border: '3px solid #aaa', padding: '10px, 0px, 0px, 0px' , verticalalign: 'middle' }
});
var btn = document.getElementById("ctl00_ContentPlaceHolder1_btnHidden");
btn.click();
});
});
Button:
<asp:Button ID="btnSave" runat="server" Text="Save" CssClass="button" Width="200" />
Since you're in an UpdatePanel, use .live() here, like this:
$(function() {
$('#<%= btnSave.ClientID %>').live('click', function(e) {
e.preventDefault();
$.blockUI({
message: '<div><h1><img src="Images/busy.gif" /> Please wait...</h1></div>',
css: { textAlign: 'center', border: '3px solid #aaa', padding: '10px, 0px, 0px, 0px' , verticalalign: 'middle' }
});
var btn = document.getElementById("ctl00_ContentPlaceHolder1_btnHidden");
btn.click();
});
});
.live() listens at the document level for a click from btnSave to bubble up...so it works when the element is added, removed, replaced, etc. (and your UpdatePanel is replacing it each postback), where as .click() attaches directly to the element...and that click handler is lost when the element is replaced.

Categories

Resources