jQuery Dialog not appearing when called - javascript

I am trying to get a modal loading dialog to pop up while I make an ajax call but it is not showing up in the onClick function. If I slow it down with firebug and step through the loading panel will show up. Is this just javascript running ahead of itself? Is there a better way to do this?
$(function(){
$("#loading_panel").dialog({
modal:true,
position:'center',
minHeight:40
});
$("a.view-in-frame").click(function(){
$("#loading_panel").dialog('open');
$("#tabs").hide();
var blog = $(document.createElement('div')).attr('id', 'blog').load(('blog_reader.php?blog='+this.href)), $("#loading_panel").dialog('close'));
$("#content_wrap").append(blog);
return false;
});
})

Just an idea, try setting the 'autoOpen' to false when creating the dialog:
$("#loading_panel").dialog({
modal:true,
position:'center',
minHeight:40,
autoOpen:false
});
At the moment you are telling the dialog to open when it is created. This should prevent that behaviour.

#ErsatzRyan
Have you tried set your javascript function to load after your document is ready?
Like this:
$(document).ready(function(){
//Your functions
});
And as #Nat Ryall said, you must set your autoOpen to false, otherwise your dialog won't open twice.
And another thing, try to call your $(".selector").dialog("open") after you done everything. You're telling your function to call your dialog before it has loaded it's content.

Related

Html.ActionLink: popup(custom), then redirect

I want to show popup when person clicks on button(which is already done with Html.ActionLink - older code; popup only shows if session variable equals some value...this part is alredy figured out) and is then redirected or new view is returned(this is done in controller).
I have Html.ActionLink(<button name>, <controller>, <action>) and out of that with help of other answers here I made Html.ActionLink(<button name>, <controller>, <action>, null, new { onlick: 'myPopup();'}) where myPopup() is function that creates qjuery modal popup.
But my issue is that sometimes popup doesn't even show or only for few seconds. I think that it's because javascript is async and controller is faster so it returns before javascript code is executed. Does anyone know how to execute javascript code first and then controller code.
I tried to Html.ActionLink(<button name>, <controller>, <action>, null, new { onlick: 'myPopup();return false;'}) as return false should stop default behavior(redirecting to Controller/Action) and then in jquery code I put ajax redirect to controller when button OK in popup is clicked. But problem is I can't seem to make this work, it may be even wrong way?
Any suggestions how to add this function?
Hi and welcome to SO :)
You would need to handle the redirect within your myPopup() function. Assuming you have a "continue" button within your modal. One way you could do it is -
$('#actionLinkId').click(function (e) {
e.preventDefault();
var link = $(this).attr('href');
$('#continue').attr('href', link);
$('#yourModalId').modal();
});

Execute JavaScript in a modal window

I have the following JS code:
<script type="text/javascript">
$(document).ready(function () {
var items = "<option value='0'>Select</option>";
$('#DistrictID').html(items);
});
</script>
This populate a dropdownlist with the value Select, the thing is, this dropdownlist appears in a form that it's called once the user clicks a button and then a modal windows opens, with the form in it.
But since it is mark as
$(document).ready
This JS won't execute with the modal, since the document is already 'ready'. How can I achieve this?
Thanks in advance!
Regards,
You can easily achieve this using bootstrap modal events. You can use following code snippet to achieve your objective:
$(document).ready(function () {
$('#myModal').on('shown.bs.modal', function (e) {
var items = "<option value='0'>Select</option>";
$('#DistrictID').html(items);
});
});
For reference Please check bootstrap modal events.
A useful way to load and execute javascript after the page is loaded, like modal window show ups, is to use ajax getScript function, which Loads (and executes) a JavaScript from a server using an AJAX HTTP GET request through a pre-defined function in main page.
function loadJS(lnk){
$.getScript(lnk);
}
it can be a general way to load any script in a fully loaded page.
One solution is to use jQuery event.on
from this blog post https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html
I will quote the author, because I think it's a very neat explanation.
We can’t register a listener to an element that doesn’t exists.
A work around is to register the listener to an element that will
always exist in the page context. The #modal-book is the closest
element. It is a little bit more complex what happen, but long story
short, the HTML events propagate to the parents elements until it
reaches the end of the document.
More here: https://api.jquery.com/on/
Try something like this:
$('#idofselectelement').change(function() {
//grab the selected option and then do what you want with it.
});

how to run a jQuery function after certain element is displayed

I have a modal that is displayed only once (like a dialog box) after user logged-in firstly. And also I've got a function in that modal file that is supposed to run if modal is displayed.
Here is function:
$('#some_element').(function someFunc() {
console.log("gUM is used now");
//some stuff to do
});
I tried on('click') and it works fine. But I don't need it.
Also, I tried on('load'), but it works before modal is displayed.
Any help will be appreciated. Thanks in advance.
Hello i think you can use events. for example for jquery dialog there is many events and function to know if dialod is open http://api.jqueryui.com/dialog/#method-isOpen and some events like open or beforeClose or you can use jquery to detect if the element is visible $("#SomeElement").is(":visible")
Not an ideal solution but you could start a timer in on load, and have it run a function every half second to check if the modal is visible:
var checkModalTimer;
$(document).ready(function() {
checkModalTimer = setInterval(function() {
if ($('modal').is(':visible')) {
// do your function
clearInterval(checkModalTimer);
}
}, 500);
});

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.

Categories

Resources