JavaScript - Clear Global Variable When Reopen Window
Similar Tutorialshello I want ask how can i declare global variable in html file , and use it in java script file . - with same value- thanks I am working with the google blogger API, and I am having an issue updating my global variable Response. I thought I understood how global variables worked, so I don't know if there is something different about the blogger API or if I'm making a dumb mistake. Code: <SCRIPT TYPE="text/javascript" src="http://www.google.com/jsapi"></ script> <script> google.load("gdata","1.x", {packages: ["blogger"]}); google.setOnLoadCallback(getMyBlogFeed); blogID = "1601946089552390859"; var feedUri = "http://www.blogger.com/feeds/"+blogID+"/posts/full?alt=json"; var Response = ""; function getMyBlogFeed(){ var myBlog = new google.gdata.blogger.BloggerService('GoogleInc-jsguide-1.0'); myBlog.getBlogPostFeed(feedUri, handleBlogFeed, handleError); } function handleBlogFeed(myResultsFeedRoot) { Response = myResultsFeedRoot.feed.entry[0].content.$t; } function handleError(e) { alert("There was an error in getBlogPostFeed"); alert(e.caue ? e.cause.statusText : e.message); } alert(Response); </SCRIPT> Here's what I think SHOULD happen: Response is initialized as a global variable with a value of "" setOnLoadCallback calls getMyBlogFeed which creates a blog object, then calls getBlogPostFeed which calls handleBlogFeed. handleBlogFeed stores a new string to global variable Response an alert pops up with the value of Response (as given by handleBlogFeed) What actually happens is that the alert pops up with the original value of Response. I know that I can issue the alert inside handleBlogFeed, but that isn't the issue. My issue is that I'd like to use Response in other functions, but it isn't being updated as a global variable. What am I doing wrong that Response isn't updating? On a related note, is there a way to return a variable from my handleBlogFeed function? How would I do that? -- I can't seem to figure it out. Thanks! P.S. I recognize that the best place to ask this is the blogger developer group. I've already posted this there, and no one has responded yet. Hi, I have popup window and i want when i press on "Clear" table content clear .. I used document.writeln to write into the popup window .. see the pic : Hi, Here's a sample form: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Sample form</title> <script type="text/javascript"> function displayResult() { alert(document.myForm.myInput.value); } function getFocus() { if (document.myForm.myInput.value == document.myForm.myInput.defaultValue) { document.myForm.myInput.value = ""; } } function loseFocus() { if (document.myForm.myInput.value == "") { document.myForm.myInput.value = document.myForm.myInput.defaultValue; } } </script> </head> <body> <form name="myForm" method="get" onsubmit="return false;" action=""> <input name="myInput" value="Hello world!" onfocus="getFocus();" onblur="loseFocus();"><br> <input type="button" onclick="displayResult();" value="Display input value"> </form> </body> </html> It works with no problem, but the following doesn't: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Sample form</title> <script type="text/javascript"> var x = document.myForm.myInput; function displayResult() { alert(x.value); } function getFocus() { if (x.value == x.defaultValue) { x.value = ""; } } function loseFocus() { if (x.value == "") { x.value = x.defaultValue; } } </script> </head> <body> <form name="myForm" method="get" onsubmit="return false;" action=""> <input name="myInput" value="Hello world!" onfocus="getFocus();" onblur="loseFocus();"><br> <input type="button" onclick="displayResult();" value="Display input value"> </form> </body> </html> What's wrong with it and how can I define a global variable to be used by all the functions? Many thanks in advance! Mike I am trying to figure out how to assign a value to a global variable within a function and can't seem to figure it out. Here's my thought, Code: <script type="text/javascript"> var global1=""; var global2=""; function assign(vari,strng){ vari = strng; } </script>... <input name="box1" onblur="assign('global1',this.value)"/> <input name="box2" onblur="assign('global2',this.value)"/> ... The purpose behind this is creating a form that will work with an existing database that would normally have a text area with lots of information. I am trying to turn it into a checklist that I can run from a mobile device. The global variables woudl be used to fill in a hidden text area that would then be passed on to the database upon submission. I am trying to keep the code as compact as possible. Any ideas? Hi, Is is possible to access a global variable for use inside a function? Thanks for help in advance Mike Heres a link to the code in question http://www.scccs.ca/~W0049698/JavaTe...erlocktxt.htm# when the leftPos variable is used in the moveSlide() it somehow turns into Nan. Cant figure out why and have been racking my brain over this for a long time now.. Any help would be greatly appreciated the problem is at the end of the code(scroll to the bottom) ======================================================= Code: window.onload = makeMenus; var currentSlide = null; var timeID = null; function makeMenus(){ var slideMenus = new Array(); var allElems = document.getElementsByTagName("*"); for(var i=0 ; i < allElems.length ; i++){ if(allElems[i].className == "slideMenu") slideMenus.push(allElems[i]) } for(var i=0 ; i < slideMenus.length ; i++){ // alert(slideMenus.length) slideMenus[i].onclick = showSlide; slideMenus[i].getElementsByTagName("ul")[0].style.left = "0px"; } document.getElementById("head").onClick = closeSlide; document.getElementById("main").onClick = closeSlide; } function showSlide(){ slideList = this.getElementsByTagName("ul")[0]; if(currentSlide && currentSlide.id == slideList.id) {closeSlide()} else{ closeSlide(); currentSlide = slideList; currentSlide.style.display = "block"; timeID = setInterval("moveSlide()", 1); } } function closeSlide(){ if(currentSlide){ clearInterval(timeID); currentSlide.style.left="0px"; currentSlide.style.display="none"; currenSlide = null; } } Code: hello im trying to change a variable set outside of a function and calling the function with an onchange... i'm having problems getting the variable to change Code: <script type="text/javascript"> var price = '<?php echo $price; ?>'; function addtwo() { if(document.add.size.value == "2xl") { price = price + 2; } } </script> Hey all! Got a question I can't seem to find an answer to. I have a little JS app that is a glorified calculator which I posted the code for below. My code uses the document object to replace the html in the "content" <div> and works great. However, I want to add an inline style in order to change the background of the input (readonly field with an id of "coutput") based on either of the global variables named "MJPD" or "IJPD", (depending on the switch case selected in the user prompt at the beginning of the script.) Simplified....if the value of MJPD is less than 4.6, I want the "coutput" field's background to be red, else be green. The same goes for IJPD, except the threshold for red will be <3.83. Code and what I have tried is below. After reading the code, look below it to see what I have tried and maybe tell me what I'm doing wrong! =) Any help is greatly appreciated.......I have spent a week searching for this little answer and I can't seem to find it! Code: <script language="JavaScript"> var MJPD = 1; var IJPD = 1; function sayhello(){ // *** live test for inline JS code placement alert("IT WORKS!!! Now change me =)"); } ////////////////////////////////////////////////////// function changeScreenSize(w,h) { window.resizeTo( w,h ) } /////////////////////////////////////////////////// function iJPDCalc(form) //calculate IJPD value { var ij = parseFloat(form.IJobs.value, 10); var it = parseFloat(form.ITime.value, 10); var IJPD = 0; IJPD = (ij / it) * 8.0; form.I_JPD.value = IJPD; } ///////////////////////////////////////////////////// function mJPDCalc(form) //calculate MJPD value { var mj = parseFloat(form.MJobs.value, 10); var mt = parseFloat(form.MTime.value, 10); var MJPD = 0; MJPD = (mj / mt) * 8.0; form.M_JPD.value = MJPD; } ///////////////////////////////////////////////////// function ijpdcolor() //set bg color of coutput based on IJPD's value { if (IJPD >= 3.83) { return ("green"); } else { return ("red"); } } ///////////////////////////////////////////////////// function mjpdcolor() //set bg color of coutput based on MJPD's value { if (MJPD >= 4.6) { return ("green"); } else { return ("red"); } } ///////////////////////////////////////////////////// function startVZT3(){ var n=0; n=prompt("What would you like to do? 1: Calculate IJPD 2: Calculate MJPD 3: Exit", "Enter a value from 1-3") switch(n) { case(n="1"): document.getElementById("content").innerHTML='<FORM><h2>Combined IJPD Calculator</h2><p>Install components completed today:</p><INPUT NAME="IJobs" VALUE="3.84" MAXLENGTH="10" SIZE=10><p>Hours taken to the jobs:</p><INPUT NAME="ITime" VALUE="8" MAXLENGTH="10" SIZE=10><h4> Click the button to calculate your IJPD:</h4><INPUT NAME="calc" VALUE="Calculate" TYPE=BUTTON class="cbutton" onClick=iJPDCalc(this.form)><p>Your current combined IJPD for today is:</p> <INPUT NAME="I_JPD" class="output" style=" " id="coutput" READONLY SIZE=10></FORM>'; break case(n="2"): document.getElementById("content").innerHTML='<FORM><h2>Combined MJPD Calculator</h2><p>Trouble components completed today:</p><INPUT NAME="MJobs" VALUE="4.6" MAXLENGTH="10" SIZE=10><p>Hours taken to the jobs:</p><INPUT NAME="MTime" VALUE="8" MAXLENGTH="10" SIZE=10><h4> Click the button to calculate your MJPD:</h4><INPUT NAME="calc" VALUE="Calculate" TYPE=BUTTON class="cbutton" onClick=mJPDCalc(this.form); mjpdcolor();><p>Your current combined MJPD for today is:</p> <INPUT NAME="M_JPD" class="output" style=" " id="coutput" READONLY SIZE=10></FORM>'; break case(n="3"): alert('This page will now close...'); window.close(); break default: document.getElementById("content").innerHTML='<h1 style="padding-top: 40px; color: red;">You need to enter a value! Please try again...</h1>'; break } } /////////////////////////////////////////////////////// </script> </head> <body onload="changeScreenSize(825,775)"> <div id="wrapper"> <div id="sub_wrapper"> <br /> <br /> <input type="button" class="button" onclick="startVZT3()" value="Start VZT3 Web!" /> <br /><br /> <div id="content"> <h3 style="padding-top:60px;">VZT3</h3> </div> </div> <script type="text/javascript"> <!-- trying script to ensure function and dynamic update of this value - doesnt work 2/3/2010 --> document.write(mjpdcolor()); </script> </div> </body> OK, so on the last line of each case statement where it injects html code into the content div, in this code style=" background: ** ** " and in between the ** ** marks, I have added such things as <script type="text/javascript">document.write(mjpdcolor())</script> (or ijpdcolor, depending on which case I am working with). Theoretically, this should pull the value of MJPD (or IJPD), evaluate it for the if statement, then return the value of red or green and set the value of the background dynamically - but of course it doesnt. I have also tried different inline styles and even adding the css id and trying to link it to the mjpdcolor() function, but all to no avail. Can someone help me please?? Thanks everyone, your awesome! Hi, I am new here, it's nice to meet you guys. I am writting a javascript that need to force the user to close the current browser and then restart automatically again after some operation. Here is the case : The user will retrieve a file from the server and save it in the local drive. After that, the browser will automatically open the .pdf saved with the browser(IE) but not Adode reader. If the user wants to update the previous saved .pdf in the local drive, they will need the user to close the opened file(saved .pdf) so that new updated .pdf can be replaced to the old .pdf file. So, I need to implement a function that force the browser to close, then copy and replace the old file, then reopen the file(new and updated) again. Is there any possible way of doing this ? Please provide me some idea. I have tried to look for informations online but I just got no luck. Failed with the coding provided. Thanks in advance. P/S : The file need to be closed in order to replace it with a new one. The platform using is Windows. Hi there I'm nearly completed on a game, and want to bring in "Lives", basically, rather than the game ending, running "function EndGame ()" I want to allow the player to carry on with "Lives", 3 in fact. Basically, when the player presses a wrong tile, the game needs to carry on, until the last life, life 3 is lost, then "function EndGame ()" runs.. I believe a Global Variable needs to be used? If any help could be given that would be great, also if it could be shown in JSFiddle, that would be great! Many thanks Reply With Quote 12-18-2014, 03:56 PM #2 Dormilich View Profile View Forum Posts Senior Coder Join Date Jan 2010 Location Behind the Wall Posts 3,532 Thanks 13 Thanked 372 Times in 368 Posts Originally Posted by LONDONLAD I believe a Global Variable needs to be used? nope. you can use a global, but you should not. better use the variable/container that you store the player or game status in. I having trouble with this code, I have this timer running in a js file if the timer runs out then an alert box pops up letting the user know that they have been logged out. There is also a pop-up window and if the user press down on the key board then the timer resets. I have already done this in my test files, What I am trying to do is apply it to this other code and its a bit tricky. Below you will find my test code. test1.php PHP Code: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type="text/javascript" language="javascript"> var test2 function popup() { test2=window.open( "test2.php", "myWindow", "status = 1, height = 300, width = 300, resizable = 0" ) } </script> </head> <body> <?php echo '<a href="#" onclick="popup()" >Click Here</a>'; echo '<embed src="logout_operator.wav" autostart="false" id="logout" width="0" height="1" loop="false">'; echo '<script type="text/javascript" language="javascript" src="test.js"></script>'; echo '<script type="text/javascript" language="javascript"> function timeout(logoutSound) { var soundLogout=document.getElementById(logoutSound); soundLogout.Play(); alert("Your session is expired please login again"); location = "http://www.google.com"; } </script>'; ?> </body> </html> test2.php (pop-up window) PHP Code: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type="text/javascript" language="javascript" src="test.js"></script> </head> <body> <script type="text/javascript" language="javascript"> window.onkeydown = handle; function handle() { resetTimer(); return true; } </script> </body> </html> test.js Code: var timer = setTimeout("timeout('logout')", 5000); function resetTimer(d) { clearTimeout(timer); if (d!="done"){ if (location.href.indexOf("test2.php")!=-1){ window.opener.window.resetTimer("done"); } else{ test2.window.resetTimer("done"); } } timer = setTimeout("timeout('logout')", 5000); } What I am trying to do is apply the function and the button to this code: Code: var _h = { mi: function (link, title, ni, qi, width, height, ri) { return '<a href="' + link + '"' + (ri != null ? ' class="' + ri + '"' : '') + ' target="_blank" title="' + title + '" onclick="this.newWindow = window.open(\'' + link + '\', \'' + ni + '\', \'toolbar=0,scrollbars=0,location=0,status=1,menubar=0,width=' + width + ',height=' + height + ',resizable=1\');this.newWindow.focus();this.newWindow.opener=window;return false;">' + qi + '</a>'; } I have tried to put the test2 variable as _h but that didn't work at all. Any help would be much appreciated, thanks!!! I can't seem to figure out how to post a variable to a javascript pop-up window. I'm trying to get a the users input to post directly to the URL. For example: Code: <!--Pop-up--> <script type="text/javascript"> <!-- function expo() { window.open( "export.php?&export=<?PHP $myvar = $_POST['exportthis']; echo $myvar; ?>", "myWindow", "status = 1, height = 300, width = 300, resizable = 0" ) } //--> </script> <form action="" method="post"><input type=text value="pass-this-variable" name="exportthis"> <input type=button value="Export" name="Exp" onClick="expo()"> </form> Any suggestions? I have a search form and added the "Clear All" Button functionality...but it clears the last part of the search form display preferences....how do I only clear the checkboxes at the top of the form only and not at the bottom of the form between the <DIV> tags? I have attached a copy of the JSP page. Hi there, i have one script which is supposed to pop up a new win and after it does write a piece of text in it. This text comes from inside the HTML area: Code: (script) function popupwin(whichOne) { var width = 450; var height = 490; var left = parseInt((screen.availWidth/2) - (width/2)); var top = parseInt((screen.availHeight/2) - (height/2)); var windowFeatures = "width=" + width + ",height=" + height + ",status=no,resizable=no,location=no,titlebar=no,left=" + left + ",top=" + top + "screenX=" + left + ",screenY=" + top; newwin = window.open("spSelect.html","spSelect",windowFeatures); spSelect.document.whichOne.value = whichOne; } (calling part in html) <a href="javascript: popupwin(Souvlaki);"><img src="images/orderbutton.gif" width="100" height="20" border="0"></a> (new win place where text is supposed to appear) <input name="whichOne" readonly="readonly" type="text" class="textfield"> Sorry, this is a newbie question, and probably really dumb, but... If I create a function that looks like this... Code: function recall(tim) { setTimeout("window.location.replace('somepage.html')",tim); } ...it works fine when called. However; I want to be able to pass the page url in a variable, something like this... Code: function recall(tim, myurl) { setTimeout("window.location.replace(myurl)",tim); } ...but this creates an error, saying "myurl is not defined." Even if I simplify the code and place the url in a variable within the function... Code: function recall(tim) { var myurl="somepage.html"; setTimeout("window.location.replace(myurl)",tim); } ...I still get the "myurl is not defined" error, even tho I am defining it. Plz can someone explain what I'm doing wrong. Tkx... --paul Hey, I'm looking for a way to get a variable from a parent window in a child window. I'm aware that you can write the variable to a hidden field and then get the field's value in the child window, but I'm looking for a cleaner (all JS preferable) way of doing this. Something like this, but I believe this is an out-dated solution: Code: var str = window.opener.str; alert(str); Any solutions? Hello folks, I have a very simple problem...but stuggling with this. I have a popup window (.aspx page). It will called from a parent .aspx page. All I want to do is read the name of the parent aspx page in popup page. Based on the name of the parent window, in the page_load event of the popup window, I want to execute some code. But the only catch is that, I am not able to read the parent window name until the page_load event (of popup window) complets the execution. 1. calling popup window from parent window. Code: Code: function OpenWindow_HistoricalRuns() { var windowIncsimHistRuns = window.open('MVal.aspx', 'Market', 'width=350,height=425,scrollbars=0'); windowIncsimHistRuns.moveTo(500, 300); } In the body of the popup window the following function tries to read the parent window name: Code: function SetDisplay() { document.getElementById('<%=TextBoxSourcePageName.ClientID%>').value = window.parent.name; } In the page_load event of the popup window, I want to see what is value of TextBoxSourcePageName control. I hoped I will get 'MarketVal'. But I never get anything. Code: protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { try { if (TextBoxSourcePageName.Text == "MarketVal") } } } In my situation, I need to know the window.parent.name by the time Page_load event gets triggered on the popup window. Because I have to do some specific thing in the Page_Load event (of popup window), based on window.parent.name. So my fundamental question is, which one will get fired first in an .aspx page. 1. Javascript in the body tag or 2. Page_load event of the .aspx page. If Javascript function in the body tag gets fired first, then by the time I get to Page_Load event, I should already have whatever I need. thanks On my main page, I have a list of item ID's which are assigned variables, the list is concatenated and so the variables are always different. So another thing that gets concatenated is a link, which uses javascript/jquery to open a popout modal window which is another php file called sharepost.php. I want to be able to transfer the php variables from the main page to append them on the end of the sharepost.php URL so I can use $_GET to grab them for use. Here's what I have... not working, but I figured I'd give it a try. Code: <?php //use mysql to loop through some variables $post_id = $setvalue; $member_id = $anothersetvalue; $list .= ' <div> ' . $post_id . ' </div> <div> ' . $member_id . ' </div> <div> <a href="#" class="button" onClick="openup(); return false">Share This Post</a> </div> $the_link = " http://sharepost.php?post_id=' . $post_id . '&member_id=' . $member_id . ' "; '; ?> <HTML> <head> <script> // Displays an external page using an iframe function openup(){ var src = "<?php echo $the_link;?>"; $.modal('<iframe src="' + src + '" height="450" width="830" style="border:0">', { closeHTML:"", containerCss:{ height:150, padding:0, width:350 }, overlayClose:true, }); } </script> </head> <body> <?php echo $list;?> </body> </HTML> Code: <fieldset class="submit" style="padding-left: 200px;"> <?php if ($site_exist >= 1){ echo "<input type=\"submit\" name=\"submit\" value=\"Update\">"; } else { echo "<input type=\"submit\" name=\"submit\" value=\"Submit\">";} ?> <!-- This is the button I am having trouble with. --> <input type="button" name="delete" value="Delete" onClick="return confirmSubmit()"> </fieldset> </form> <script type="text/javascript"><!-- function confirmSubmit(){ var agree=confirm("Are you want to delete this site from our index?"); if (agree) return true ; else return false ; } // --> </script> Not entirely sure which forum this should go in, since the problem could probably be fixed with HTML, PHP or Javascript. Anyway, I have the confirmation window working. What I need is for the button to post a variable (siteDelete = 'true') when it is pressed. I would prefer to do that part without javascript, but I want the data to be posted after and only after the confirmation window returns true. I can do that with a submit button, but I'm not sure what code to use and where to use it when using a non-submit button. |