Execute JavaScript in a modal window - javascript

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.
});

Related

ready function triggers in every page

I have a rails app, if the user is not logged in, I am redirecting to a page, which has one br tag with a class. Like this
<br class="logged">
In the Javascript on ready of that function, I am triggering a modal as follows.
$(document).ready(function(){
$('.logged').ready(function(){
$('#open-login').click();
});
});
This is working fine, except this modal is getting triggered on every page of the app. I mean that br tag is there in only page of the app, how it is ready for every page is what I don't understand. If anyone can tell what went wrong with my approach, it would be of great help.
ps: It's rails application
You can try this:
$(document).ready(function(){
if ($('.logged').length > 0)
$('#open-login').click();
}
});
Into if condition you can declare an element of specific page and in only that page you can execute an action.
The jQuery .ready() method can only be called on a jQuery object matching the current document. Attaching it to a $('.logged') selector still makes its handler function get called when the document is ready - it doesn't care about the selector.
MarcoSantino's answer will work for your needs, although you may find it cleaner to add the logged-in class to the body tag instead of inserting a new br tag, and then use the following in your JavaScript:
$(document).ready(function(){
if ($(body).hasClass('logged-in')) {
$('#open-login').click();
}
})

JQuery Mobile do X to every div with given class

I'm building a JQuery mobile site which has an image slider on 2 pages. The sliders are activated using the following JS:
$(function () {
$("#slider").excoloSlider();
});
where '#slider' is the name of the div that gets rendered as the slider.
I have this slider on the 2 pages and have given both the same id, and don't want to insert the above code into both pages. To make things easy I want to be able to make add the above code into a.js file that I'm referencing at the top of both pages.
However, the script only kicks in when one of the pages are the first page to be navigated to. So, I assume this means the code is only being called in the once, and due to the AJAX loading of the subsequent page, it isnt called when this new page loads.
So, how can I run the code to affect any/all pages which feature the slider?
I dont know how many times you have to call .excoloSlider(); function. In case you have to call it each time the page is visited, then you need to use any of these page events, pagecontainershow or pagecontainerbeforeshow.
If you use pagecontainershow, you can run .excoloSlider(); on #slider even if you have the same id in a different page. This way, you specify in which page to look for #slider.
$(document).on("pagecontainershow", function () {
var activePage = $.mobile.pageContainer.pagecontainer("getActivePage");
/* check if #slider is within active page */
var slider = activePage.find("#slider").not(".slider");
if(slider) {
slider.excoloSlider();
}
});
Update
I have added .not(".slider") selector to exclude already rendered slider. The function .excoloSlider() will be called on new sliders only.
Demo
Try to use class instead of id since id is unique, then you can change your jQuery code to:
$(function () {
$(".slider").excoloSlider();
});
Use jQuery Mobile API for the navigation system
$(window).on( "navigate", function( event, data ) {
$("#slider").excoloSlider();
});
Edit
Use pageinit
From the jQM docs:
Important: Use $(document).bind('pageinit'), not $(document).ready()
The first thing you learn in jQuery is to call code inside the
$(document).ready() function so everything will execute as soon as the
DOM is loaded. However, in jQuery Mobile, Ajax is used to load the
contents of each page into the DOM as you navigate, and the DOM ready
handler only executes for the first page. To execute code whenever a
new page is loaded and created, you can bind to the pageinit event.
This event is explained in detail at the bottom of this page.

On Click: Open a Pop-up Div on a Different Page

On page1.php I have a click event that causes the user to be redirected to page2.php. It goes something like this:
$("#someButton").click(function() {
window.location = "page2.php";
});
And that works great. But what I really want is to open a hidden, UI-blocking <div> on page2. The user can already open this <div> manually by clicking another button on page2, that goes something like this:
$('#someOtherButton').click(function() {
$("#pageContainer").block({message: $("#theDivIWant2See")});
});
Can I make a click event from the JavaScript on one page call the JavaScript on another? Or will I need to add in some HTML-parsing to pass information between pages? (I'm not looking for a JavaScript hand-out here, just a strategy to help me move forward.)
When you redirect from the first page, add a querystring value in your url. and in the second page, using your server side page language, set in in a hidden field and in the document ready event check the value of that hidden field. If the value is expected, call a javascript function to show the popup.
Some thing like this
$("#someButton").click(function() {
window.location = "page2.php?showpopup=yes";
});
and in page2.php set it (forgive for errors, i am not a php guy)
<input type='<?php $_GET["showpopup"] ?>' id='hdnShow' />
and in the script
$(function(){
if($("#hdnShow").val()=="yes")
{
//Call here the method to show pop up
}
});
You need to do your stuff when DOM for page2 is ready. You can use jQuery's ready function for that.
$(document).ready(function() {
// put code for showing your div here
});
Hope that helps.
Could you pass a query string argument or assign a cookie that the other page could then check when the document loads? If the value exists then present a modal dialog (e.g. jQuery UI Modal Popup)
http://jqueryui.com/demos/dialog/

Running javascript whenever UpdatePanel refreshes

I am using an asp.net update panel to refresh the content on a page when a menu item is selected.
Within the content that is updated are images which have a javascript reflection function which is triggered with the following line of code:
window.onload = function () { addReflections(); }
This runs fine when the page is first loaded but not when a menu item is selected and the update panel is run.
On previous projects using jquery code I have replaced document.ready with function pageLoad but there is no document.ready on this page.
Like this:
<script>
// ASP.NET AJAX on update complete
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function(sender, args) {
// your code here, eg initToolTips('/Common/images/global/popup3.gif');
});
Basically, it's because that event isn't triggered by an update panel refresh.
There are ways to achieve this behaviour though, Ajax.Net has an EndRequestHandler function that you can hook into.
Here's a good example:
http://zeemalik.wordpress.com/2007/11/27/how-to-call-client-side-javascript-function-after-an-updatepanel-asychronous-ajax-request-is-over/
i think u should use
function pageLoad(sender, arg) {
if (!arg.get_isPartialLoad()) {
// in first load only
}
//every time the update panel refreshed
}
Regards
Take a look to this event:
http://msdn.microsoft.com/en-us/library/bb383810.aspx
window.onload is fired when the entire page is loaded. UpdatePanel uses an AJAX approach, so whenever it's updated and round trip ends, the page remains loaded and only a portion of this has been updated.
In other words, you need to do that "when a request to the server ends".

jQuery code repeating problem

I have a piece of code in jQuery that I use to get the contents of an iFrame after you click a link and once the content is completed loading. It works, but I have a problem with it repeating - at least I think that is what it is doing, but I can't figure out why or how.
jQuery JS:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
$("#fileuploadframe").load(function(){
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{action:"savePage",html:response, id: theID},
function(data){
alert(data);
});
});
});
HTML Links ( one of many ):
<a href="templates/1000/files/index.php?pg=0&preview=false"
target="fileuploadframe" class="pageSaveButton" rel="0">Home</a>
So when you click the link, the page that is linked to is opened into the iframe, then the JS fires and waits for the content to finish loading and then grabs the iframe's content and sends it to a PHP script to save to a file. I have a problem where when you click multiple links in a row to save multiple files, the content of all the previous files are overwritten with the current file you have clicked on. I have checked my PHP and am pretty positive the fault is with the JS.
I have noticed that - since I have the PHP's return value alerted - that I get multiple alert boxes. If it is the first link you have clicked on since the main page loaded - then it is fine, but when you click on a second link you get the alert for each of the previous pages you clicked on in addition to the expected alert for the current page.
I hope I have explained well, please let me know if I need to explain better - I really need help resolving this. :) (and if you think the php script is relevant, I can post it - but it only prints out the $_POST variables to let me know what page info is being sent for debugging purposes.)
Thanks ahead of time,
Key
From jQuery .load() documentation I think you need to change your script to:
$(".pageSaveButton").bind("click",function(){
var theID = $(this).attr("rel");
var lnk = $(this).attr("href");//LINK TO LOAD
$("#fileuploadframe").load(lnk,
function(){
//EXECUTE AFTER LOAD IS COMPLETE
var response = $("#fileuploadframe").contents().find("html").html();
$.post("siteCreator.script.php",
{
action:"savePage",
html:response,
id: theID
},
function(data){alert(data);}
);
});
});
As for the multiple responses, you can use something like blockui to disable any further clicks till the .post call returns.
This is because the line
$("#fileuploadframe").load(function(){
Gets executed every time you press a link. Only add the loadhandler to the iframe on document.ready.
If a user has the ability via your UI to click multiple links that trigger this function, then you are going to run into this problem no matter what since you use the single iframe. I would suggest creating an iframe per save process, that why the rendering of one will not affect the other.

Categories

Resources