How to close browser window with a dialog popup using jQuery function? - c#

I am working on a project but need to know how to close the browser window and also show a dialog box if I would like to exit the page, using jQuery.
Thanks Rick, this helps, it brings up the dafault chrome pop up dialog, I am trying to customize it to use my dialog in my javascrip file so it can prompt it when the user closes the page.. here is my code function ConfirmationDialog(baseURI) {
var dialog = jQuery('Are you sure you want to exit this form without saving?').attr({
type: 'hidden',
id: 'dialog'
}).css("display", "none").appendTo('body');
jQuery("#dialog").dialog({
resizable: false,
height: 140,
modal: true,
title: 'Confirm',
buttons: {
"Yes": function () {
window.location = baseURI;
// jQuery(this).dialog("close");
},
Cancel: function () {
jQuery(this).dialog("close");
}
}
});
return false;
}

To close browser:
window.close();
To prompt user:
window.addEventListener("beforeunload", function (e) {
var message = "Are you sure you want to leave?";
(e || window.event).returnValue = message;
return message;
});

Related

Prevent asp popup window from pop up blocker

I am using the following code to get popup window in asp .net before sending text in database. But due to popup blocker pop up dose not come.
string strPopup = "<script language='javascript' ID='script1'>"
// Passing intId to popup window.
+ "window.open('sharepopup.aspx?data=" + HttpUtility.UrlEncode(intId.ToString())
+ "','new window', 'top=90, left=200, width=500, height=500, dependant=no, location=0, alwaysRaised=no, menubar=no, resizeable=no, scrollbars=n, toolbar=no, status=no, center=yes')"
+ "</script>";
ScriptManager.RegisterStartupScript((Page)HttpContext.Current.Handler, typeof(Page), "Script1", strPopup, false);
cmd = new SqlCommand("Insert Into ChatTB values(column names) ", con);
You can't - because that's what popup blockers do: they block popup windows (i.e. calls to window.open or invocations of target="_blank" links) unless it is directly in response to a user mouse action.
Alternatively you can use Jquery
$("#dialog-message").dialog({
modal: true,
draggable: false,
resizable: false,
position: ['center', 'top'],
show: 'blind',
hide: 'blind',
width: 400,
dialogClass: 'ui-dialog-osx',
buttons: {
"ok": function() {
$(this).dialog("close");
}
}
});
Here is the fiddle

How to display the content in popup window?

Iam creating a button "SampleTest", which wil have to show the model data and "GoBack" button in popup window.But it displaying the content in full screen popup also overriding.Like,
i have my jquery like,
$('#SampleTest').button().click(function () {
var options = {};
options.type = "POST";
options.url = "/Dashboard/SampleTest/";
options.dataType = "json";
options.contentType = "application/json";
options.success = function (data) {
alert(data);
$(".popup").html(data);
$(".trasparentDiv").show(data);
$(".popup").show(data);
};
$.ajax(options);
});
Do i need to include any function in my jquery for popup window.Kindly tell me what to do in this case.
Please include JQuery UI script with appropriate version into your page after JQuery core script file.
Jquery UI CDN Path from JQuery: https://code.jquery.com/ui/
More help about Jquery Popup: http://jqueryui.com/dialog/
i have rewritten the code like,
function LoadSampleTest() {
alert('sample');
$("<div></div>")
.attr('id','SampleQuestionDiv')
.appendTo("body")
.dialog({
modal: true,
Close: function () {
$(this).dialog("close");
},
Width: 1000,
height: 800,
title: "Sample Test"
}).load("/dashboard/sampletest/");
Its works good.Instead of OK button, i have given close option to close the popup.

Return response to onClientClick based on user button selection

I have an onClientClick event like so:
OnClientClick="return getErrors();" - this of course is within an
the body of the function is:
function getErrors() {
var errorString = "some errors";
return $('<div id="dialog-message" title="Required"><p>' + errorString + '</p></div>').dialog(
{
modal: true,
width: 700,
buttons:
{
Ok: function () {
$(this).dialog("close");
return callback_ErrorAction(0);
},
Cancel: function () {
$(this).dialog("close");
return callback_ErrorAction(1);
}
}
});
return false; //omit this and OnClientClick gets undefined response variable
}
Also the callback function is defined as:
function callback_ErrorAction(bool)
{
if (bool == 0) {
return true;
}
else if (bool == 1) {
return false;
}
}
The problem is I need the OnClientClick response to be based on user response, clicking Ok or cancel but the current solution returns a response to onClientClick before the user even has a chance to select OK or Cancel. Thanks for helping
You can't return the user's response through OnClientClick because the jQuery dialog uses callbacks.
Instead, you need to always return false from your OnClientClick method and manually fire a postback when you need to:
function getErrors() {
var errorString = "some errors";
$('<div id="dialog-message" title="Required"><p>' + errorString + '</p></div>').dialog(
{
modal: true,
width: 700,
buttons:
{
Ok: function () {
// Are you sure you want to close the dialog here? It will disappear when the page refreshes anyway
$(this).dialog("close");
// Manually trigger the postback
__doPostBack('<%= btnSubmit.UniqueID %>', '');
},
Cancel: function () {
$(this).dialog("close");
// Error, do nothing as we will cancel the postback by default
}
}
});
return false;
}
See this question for more information on manually invoking the doPostBack call.

Get value of jquery ui dialog in code behind

I have a jquery ui dialog that has a radio button list on it. I need to call a server side method when the user clicks ok and I need to pass the selected value. I tried doing it by calling an ajax method on and passing the selected value as a parameter. This worked great (the value was passed) but I could not access a cookie from the method (got error - Request is not available in this context), which makes sense being that this is an ajax request. Here is the code:
$("#dialogReject").dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Reject": function () {
var value = $(this).find('input:checked').val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/myPage.aspx/RejectDocumentWM",
data: "{'rejectReason':'" + value + "'}",
dataType: "json",
success: function (data) {
alert('success');
},
error: function (result) { alert('error'); }
});
$(this).dialog('close');
},
Cancel: function () {
$(this).dialog("close");
}
}
});
RejectDocument():
[WebMethod]
public static void RejectDocumentWM(string rejectReason)
{
MyNamespace.myPage page = new MyNamespace.myPage();
page.RejectDocument(rejectReason);
}
protected void RejectDocument(string rejectReason)
{
batch batch = (batch)Session["Batch"];
if (client.RejectDocument(batch.GetCurrentDoc().icn, rejectReason, Request.Cookies["username"].Value)) //here is where I get the error
{
NextDocument();
}
}
I tried doing it by putting the value into a hidden field and then calling a button click which calls a server side method. My problem here was that the hidden field's value was always blank even though it set properly in the client script. Here is the code for that:
$("#dialogReject").dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Reject": function () {
var value = $(this).find('input:checked').val();
$('[id$="hdfRejectReason"]').val(value); //this sets properly
$('[id$="btnRejectDoc"]').click();
$(this).dialog('close');
},
Cancel: function () {
$(this).dialog("close");
}
}
protected void btnRejectDoc_Click(object sender, EventArgs e)
{
batch batch = (batch)Session["Batch"];
if (client.RejectDocument(batch.GetCurrentDoc().icn, hdfRejectReason.Value, Request.Cookies["username"].Value))
//hdfRejectReason.Value is blank
{
NextDocument();
}
}
Any ideas for me? I am at my wits end.
Thanks!
First of All, is this hf is in 'popup' or in 'main page' section?
Second, in stackoverflow, we discused and set other (better?) way to set hidden field value in jQuery:
<div class="hfFoo-wrap">
<asp:HiddenField runat="server" ID="hfFoo" />
</div>
function FooBarFunction() {
var hfFoo = $('.hfFoo-wrap input[type=hidden]');
hfFoo.val('Bar');
var isBar = hfFoo.val();
}
Maybe in btnRejectDoc_Click have other 'null' or 'empty' params?
Third: I prefere FrameDialog with 'aspx' page and 'callback delegate'.
create popup as 'aspx' page
open popup from 'main page' by jQuery as jQuery.FrameDialog
close dialog from 'aspx-popup' as 'close popup' (jQuery.FrameDialog.closeDialog();)
on 'main page' catch callback delegate (with params from popup) and set hidden field there

open in new tab of browser programmatically

i have a login page in fancy box and on click of login i want the secure pages open in the new tab
and uses this code
// on code at btnlogin_click
FormsAuthentication.RedirectFromLoginPage(loginID, false);
string redirectTo = GetResPath("/webPages/Default.aspx");
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "add2", "parent.jQuery.redirTo='" + redirectTo + "'; parent.jQuery.fancybox.close();", true);
//on aspx page
<script type="text/javascript">
$(document).ready(function () {
$('[id*=logn_btn_new]').fancybox({
'width': 480,
'height': 280,
'padding': 10,
'margin': 10,
'hideOnOverlayClick': false,
'scrolling': 'no',
'autoScale': false,
'transitionIn': 'none',
'transitionOut': 'none',
'type': 'iframe',
'onClosed': function () {
try {
if ($.redirTo != null && $.redirTo.length > 0) {
var pop = window.open($.redirTo, '_newtab');
if (pop == null) {
alert("Please allow popups.");
}
}
}
catch (err) {
alert(err);
}
}
});
});
</script>
and redirTo is hidden fielld.
i am not able to open page in new tab can anybody help?
This is a difficult one, as it is something that is controlled by the user's web browser settings.
The method that you are using is specific to FireFox and will indeed open a new tab. But this can still be overridden by the user's settings.
However to get the same effect in other browsers here is an article for IE Open a new tab in IE through Javascript
It is worth considering why you need to do this. Users may be confused if you open a new tab / window without informing them. Is it possible to not open a new window and keep everything in the same page? Then you know that people logically will have the same results to an extent.
I hope this helps!

Categories

Resources