Jquery: How to window.open() with no valid href? - javascript

I have web page on which I display a lot of summary information. I would like to be able to, by clicking a right button or link, to open up a new window and display the underlying data.
For many reasons I cannot request the underlying data again from the server once the summary information page is generated
What I would like to achieve is:
Embed the underlying data in a hidden
table in the summary page
On thesummary page I also provide a 'drill
down' button
Open a new window upon a click of
this button
Inject the content of the hidden
table into the new windows.
What I want to learn are:
What to pass to the href parameter
of the window.open(href) function?
How to get a reference to the new
window and inject the content?
I am using jquery 1.5.2

You should pass about:blank.
open returns a new window object; you can write to its document.
However, you should consider using a modal dialog, such as jQuery UI Dialog, instead.

I'd look at using the jQuery UI dialog widget and open a dialog rather than a new window. It would be dead simple to copy stuff from the DOM into the dialog when it opens.
$('.drilldown-button').click( function() {
$('<div title="Details"></div>').dialog({
autoOpen: true,
modal: false,
open: function() {
$('.hidden-details').clone()
.appendTo($(this))
.show();
// maybe add some handlers, etc.
},
buttons: {
'Close': function() { $(this).dialog('destroy'); }
// maybe other buttons for different actions
}
});
});

Related

jquery dirty record, would like the jquery ui modal

I'm using this to test if a form is dirty.
It defaults to the standard browser confirmation asking if you are sure you want to navigate away from this page. On the jquery dirtyforms site it has a section that says you can use the jquery ui modal form.
So I tried adding a section (a div) like so:
<div id="unsavedChanges" title="Save Changes?">
<p>You've made changes to this page. Do you want to leave this page without saving?</p>
</div>
And then I added what their code looked like:
$.DirtyForms.dialog = {
selector: '#unsavedChanges',
fire: function(message, dlgTitle) {
$('#unsavedChanges').dialog({ title: dlgTitle, width: 350, modal: true });
$('#unsavedChanges').html(message);
},
bind: function() {
$('#unsavedChanges').dialog('option', 'buttons',
[
{
text: "Stay Here",
click: function(e) {
$.DirtyForms.choiceContinue = false;
$(this).dialog('close');
}
},
{
text: "Leave This Page",
click: function(e) {
$.DirtyForms.choiceContinue = true;
$(this).dialog('close');
}
}
]
).bind('dialogclose', function(e) {
// Execute the choice after the modal dialog closes
$.DirtyForms.choiceCommit(e);
});
},
refire: function(content) {
return false;
},
stash: function() {
return false;
}
};
Although I am not sure where they want me to place that (I originally placed it outside of document.ready. However, after running this and making a change to my form and navigating away I see that it still is using the browser confirmation instead of jquery ui dialog box. What am I doing wrong here?
You can only popup a custom dialog if the user is trying to leave by clicking an anchor or other element on your page.
Then you could just intercept the click on all anchors etc, prevent it, pop up a custom dialog to confirm. In other words, when someone is clicking an element on your page, you're in control and can do pretty much whatever you want.
However, when the user is trying to leave by closing the tab or browser, you can not stop them with javascript, as it would be extraordinary annoying if websites could do that.
The only way to prompt a user that is leaving by closing the tab/browser window is to use the onbeforeunload event, and that event can only be used with the native confirm dialog, there is no way to use a custom dialog or stop the user or do anything else really, as that could lead to certain websites creating systems where you could never really leave the site.
From the README:
Dirty Forms will alert a user when they attempt to leave a page without submitting a form they have entered data into. It alerts them in a modal popup box, and also falls back to the browser's default onBeforeUnload handler for events outside the scope of the document such as, but not limited to, page refreshes and browser navigation buttons.
(emphasis mine)
If you want to show a modal for this kind of things, well, you simply can't. (The reason why is security: it's easy to imagine a page preventing the user to close it whatever they attempt, short of killing the browser instance.)
Additionally, the "but not limited to" bit is intriguing: I would ask the plugin's author for details on what exactly this covers, as it might overlap with your use-case.

events calendar using jquery

I am building an appointments calendar using the fullCalendar jquery plugin and backbone.
I am reading this tutorial here about it:enter link description here
In the section "Let’s start a dialog" code is shown as to how to create a modal box and enter a new event,the code is based on the dialog widget of the jquery UI,enter link description here
here is the code specifically:
render: function() {
this.el.dialog({
modal: true,
title: 'New Event',
buttons: {'Cancel': this.close}
});
What I am trying to do is add more html in that dialog. I want to add a select element for example so that the user can choose the duration of the appointment.
The jquery documentation in http://api.jqueryui.com/dialog/ does not indicate how to do that.
In order to get a better a picture of what I want to do is to look at the modal box that appear when you go to create an event on outlook.com calendar.
Of course the data will be sent with a ajax...but that is a different topic.
The jqueryui dialog uses html content that's inside element you are applying plugin to.
I think it doesn't have built-in functionality to load content from external resources.
So you can either put html inside element before initializing dialog, or use its callbacks.
E.g. if you want to load data via ajax into it:
el.dialog({
modal: true,
title: 'New Event',
buttons: {'Cancel': this.close},
open: function(){
var thisdialog = this;
$(thisdialog).html('loading data...');
$.post('external_resouce.html',
function(data){
$(thisdialog).html(data);
}
);
}

opening jquery mobile popup on ajaxStart()

I want to show a revolving loader on ajaxStart. I've used a popup for this so that the background fades out and becomes inactive. That said, if there are other ways to achieve this (instead of using a popup), id be willing to try them out too.
The problem is, while the same function containing the AJAX call is executed on both page-load and a button click, the loader only shows up the first time - on page load. I put some console logs and verified that the ajaxStart and ajaxComplete do get triggered, but the pop-up fails to open when the AJAX call is made following the button click.
JavaScript :
$(document).ready(function(){
$( document ).ajaxStart(function() {
$("#loader").html("<img src='../images/ajax-loader.gif'/>").popup("open");
}).ajaxComplete(function() {
$("#loader").popup("close");
});
// do other stuff
loadData();
$("#button").click(function(){
loadData();
});
});
function loadData(){
//make an ajax call to fetch data
}
HTML:
<div data-role="popup" data-shadow="false" data-corners="false" class="loader1"
id="loader" data-overlay-theme="a" data-theme="none" data-dismissible="false" >
</div>
What could be the issue, or are there other solutions altogether to achieve the desired results?
First, the short answer: jQuery Mobile only supports one active popup at a time (for now). The documentation says:
Note: Chaining of popups not allowed
The framework does not currently
support chaining of popups so it's not possible to embed a link from
one popup to another popup. All links with a data-rel="popup" inside a
popup will not do anything at all.
I bumped against this issue a few times in the past and had to hack my way around it. The following code is the solution I'm currently using and works quite well so far (with jQuery Mobile 1.3.2):
$(document).on("mobileinit", function() {
$.widget("mobile.popup", $.mobile.popup, {
_trigger: function(type, event, data) {
return this._suspended ? undefined : this._super(type, event, data);
},
_openPrereqsComplete: function() {
this._super();
delete this._suspended;
},
open: function(options) {
var activePopup = $.mobile.popup.active;
if (activePopup) {
activePopup._suspended = true;
activePopup._close(true);
this.element.one("popupafterclose", function() {
activePopup.open();
});
}
this._super(options);
}
});
});
In a nutshell, that code extends the popup widget in-place to introduce a "suspended" state. All events are muted if a popup widget is in that state.
Then, the open() method is overloaded to detect if another popup is already active. If that's the case, it suspends and closes that popup (without performing any animation, so it is closed right away), then opens the new one and schedules the un-suspending and re-opening of the previous popup when the new one is closed.
Note that code binds to the mobileinit event, so it has to run after jQuery is included but before jQuery Mobile is included. Otherwise, it will be too late to extend the popup widgets that were instantiated during page initialization.

Closing jquery modal window conditionally from ASP.net code-behind

I have an ASP.net page with a link to open a jquery-based modal window (that uses colobox jquery plugin). The content of that window in loaded from another aspx file (it loads an iframe). I want to close that window when the user presses an asp:button and if some condition in my code-behind went well.
I tried many ways to close that window from code-behind like these ways:
Page.RegisterStartupScript("X", #"$(this).dialog('close');");
Page.RegisterStartupScript("X", #"var win = window.open('','_self'); win.close();");
btnDone.Attributes.Add("onclick", #"var win = window.open('','_self'); win.close();");
btnDone.Attributes.Add("onclick", #"window.open('../px/nsk.aspx', '_self', null); window.close(); ");
System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>");
System.Web.HttpContext.Current.Response.Write("self.close();");
System.Web.HttpContext.Current.Response.Write("</SCRIPT>");
but non of them can close that modal window. I'm testing on latest version of firefox.
the code behind can be supposed as sth like this:
// do some database works
if (condition)
{
// close this modal window
}
I also tried methods from jquery but none of them were a success.
Can you please telling me how can I close this window?
The other answers given provide specifics; this 'answer' attempts to be more conceptual/consultative.
Closing the Window
Closing the colorbox window is done on the client side. Both #KennyZ and #Farshid provide details on how to do this. By default, ColorBox is going to close on the press of ESC or its EXIT ui element (if used.) It's also possible to close the box programmatically, which sounds like what you need to do.
Where is the Close Action Invoked?
#KennyZ proposes an Ajax call to determine if "some condition in my code-behind went well"; that presumes you cannot tolerate a full page refresh (which seems reasonable to me) but it's something for you to decide.
If the determination of "went well" can only be done on the server, then you're looking at Ajax or a full page refresh.
Alternatively, if there is a way to make the determination on the client side, you won't need to reach back to the back end at all. Just close the colorbox window using js.
If you can provide more details about what the action is that controls closing/not closing the ColorBox window, maybe the community can help even more.
The problem seams to be solved this way:
Page.ClientScript.RegisterStartupScript(GetType(),
"CloseKey", "parent.$.colorbox.close();", true);
Use jQuery dialog with a div instead of an iframe.
Then you can use an Ajax post to run the serverside code and look at the results to decide what to do with the dialog.
Declare the dialog:
$(document).ready(function () {
jQuery("#MyDialog").dialog(
{
bgiframe: true,
autoOpen: false,
modal: true,
width: 800,
position: ['center', 100]
}
);
});
Populate the dialog and open it:
$('#OpenMyDialog').click(function () {
$.post($('url_for_dialog_contents'), function (data) {
$("#MyDialog").empty();
$("#MyDialog").append(data);
}, null, "html");
$('#MyDialog').dialog('open');
return false;
});
Submit the dialog:
$('#SubmitMyDialog').click(function () {
$.post($('url_for_dialog_action'), function (data) {
if (data.success == true) { $('#MyDialog').dialog('close'); }
}, null, "json");
});
I'm sure you'll need a lot more code in the submit dialog, but this is the general idea.

How to return value from html popup

I need a terse, clean way to implement this in asp.net mvc (+/- jquery or js)?
User clicks an element in webform A;
Webform B pops up;
User interracts with webform B;
On closing webform B, probably by a submit button, the source element in webform a is updated with a value from webform B
Thanks.
With ASP.NET MVC, I'd probably render a DIV on the page, initially hidden, perhaps via AJAX if the contents depend on values selected on the initial page. I'd use the jQuery UI dialog plugin to popup the dialog. The dialog could contain a form that submits back to the server. You could also use the onclose handler for the dialog to both copy values from the inputs in the dialog for use on the rest of the page. If you populated the dialog via AJAX you could have the server generate the HTML -- say by rendering a partial view and returning it -- or return json and generate the dialog on the fly in the browser.
I've resorted to using cookies. I've found this to be the only reliable way to do this. I'm using GrayBox for my dialog, so I have a function in the dialog that looks like this:
function selectValue(id, name) {
SetCookie("_someuniqueprefix_RetID", id);
SetCookie("_someuniqueprefix_RetValue", name);
parent.parent.GB_CURRENT.hide();
}
Then in my calling page I am launching the dialog which displays a partial in the GrayBox:
$(function() {
var selectUrl = '/_somecontroller/Select';
// attach a method to the chooseButton to go and get a list of
// contact persons to select from
$("#chooseButton").click(function() {
GB_showCenter('Select My thing', selectUrl, 500, 620, function() {
var id = GetCookie("_someuniqueprefix_RetID");
var value = GetCookie("_someuniqueprefix_RetValue");
DeleteCookie("_someuniqueprefix_RetID", "/", "");
DeleteCookie("_someuniqueprefix_RetValue", "/", "");
$("#MyID").val(id);
$("#MyName").val(value);
});
});
});
Also you'll need to grab a function off the web for SetCookie and GetCookie
Hope that helps
You can use javascript from the popup window to call functions on the opener via window.opener. So your popup could call a function on the parent page to pass the data back when the user clicks the submit button.
I'm not sure what your requirements are, but IMO using ajax for this sounds like overkill. If all you need is some form data from the popup webform passed to the opener webform, then there's no need to make a call to the server.

Categories

Resources