JavaScript - Variables Inside A Function Aren't Global?
Forgive but I'm quite a beginner at JS . . .
Anyway, on my website I've got a form, and then a script that validates the form. The script for validation is inside a function. The problem is that I have another script outside of the function that generates random numbers to make sure there's not a spambot submitting the form. I set a variable called 'answer' as the correct answer, but for some reason, the variable won't be read when I put it inside the original function to make sure the user got it right. How should I go about doing this? Thanks, Raybob Code: <!-- THIS SCRIPT ENSURES FIELDS ARE FILLED OUT CORRECTLY --> <script type="text/javascript"> var x1 = Math.floor(Math.random()*11); var x2 = Math.floor(Math.random()*11); var ans = x1+x2; </script> <script type="text/javascript"> <!-- function validate_form ( ) { var valid = true; var at = document.newaccount.email.value.indexOf ("@"); var dot = document.newaccount.email.value.lastIndexOf ("."); if ( document.newaccount.name.value == "" ) { document.getElementById('noname').style.display = 'inline'; valid = false; } if ( at < 2 || dot < at+2 || dot+2 >= document.newaccount.email.value.length ) { document.getElementById('wrongemail').style.display = 'inline'; valid = false; } if ( document.newaccount.password.value == "" ) { document.getElementById('nopassword').style.display = 'inline'; valid = false; } if ( ( document.newaccount.password2.value == "" ) && ( document.newaccount.password.value !== "" ) ) { document.getElementById('nopassword2').style.display = 'inline'; valid = false; } if ( ( document.newaccount.password.value !== document.newaccount.password2.value ) && ( document.newaccount.password.value !== "" ) && ( document.newaccount.password2.value !== "" ) ) { document.getElementById('nomatch').style.display = 'inline'; valid = false; } if ( ( document.newaccount.password.value.length < 8 ) && ( document.newaccount.password.value !== "" ) ) { document.getElementById('passwordlength').style.display = 'inline'; valid = false; } if ( ( document.newaccount.agree[0].checked == false ) && ( document.newaccount.agree[1].checked == false ) ) { document.getElementById('noagree1').style.display = 'inline'; valid = false; } if ( ( document.newaccount.agree[0].checked == false ) && ( document.newaccount.agree[1].checked == true ) ) { alert ( "Sorry, but you must agree to the terms and conditions before creating an account." ); valid = false; window.location = "/terms.html" } if ( document.newaccount.spamcheck.value == "" ) { document.getElementById('nomath1').style.display = 'inline'; valid = false; } if ( ( document.newaccount.spamcheck.value !== ans ) && ( document.newaccount.spamcheck.value !== "" ) ) { document.getElementById('nomath2').style.display = 'inline'; valid = false; } if ( (!document.newaccount.store.checked) && (!document.newaccount.share1.checked) && (!document.newaccount.share2.checked) ) { document.getElementById('noinfo').style.display = 'inline'; valid = false; } return valid; } //--> </script> <!-- END OF SCRIPT --> Code: <form name="newaccount" onsubmit="return validate_form ( );" action="/submitted.html" method="get" > <center> <table style="text-align:center;" ><tr><td> What's <script type="text/javascript"> document.write (x1 + " " + "+" + " " + x2); </script> ? <input type="text" size="5" name="spamcheck" /></td></tr></table> <br /> <br /><br /> <input type="submit" name="send" value="Submit" /> </center> </form> Similar TutorialsHi, Is is possible to access a global variable for use inside a function? Thanks for help in advance Mike 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> Ok i'm really new at this so i apologize beforehand if i ask a stupid question or anything. I'm working on a project that displays a GUI asking for a name as well as grades. when you enter them all it runs the grades through a formula and opens another frame with the results. I don't need any help building the GUI what i need help on is I cannot for the life of me find out how to access the variable from another frame. Everything i've seen online tells me to set the variable outside the class but i need to run the formula inside because the grades come from the user. Sorry if my code is messy, like i said i'm very new at this Code: // Loads all neccesary plugins import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SInfo extends JPanel { // Setting all text fields, labels and button public JButton submitInfo; public JLabel SNamel, Asign, Asignl, Asign1l, Asign2l, Asign3l, Asign4l, Asign5l, Asign6l, Asign7l, Asign8l, Asign9l, Asign10l, Folderl, Projectl, Project1l, Project2l, Project3l, Project4l, GProjectl, blank, blank1, Sname, AsgnAvg, ProjectAvg, TotalAvg; public JTextField SName, Asign1, Asign2, Asign3, Asign4, Asign5, Asign6, Asign7, Asign8, Asign9, Asign10, Folder, Project1, Project2, Project3, Project4, GProject; double a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, p1, p2, p3, p4, gp, fldr, asgnAvg, projectAvg, totalAvg; public SInfo() { setLayout (new GridLayout (20,2)); // Sets the text for the labels { blank = new JLabel (""); blank1 = new JLabel (""); SNamel = new JLabel ("Student Name: "); Asign = new JLabel (""); Asignl = new JLabel ("--------Assignment Grades--------"); Asign1l = new JLabel ("Assignment 1: "); Asign2l = new JLabel ("Assignment 2: "); Asign3l = new JLabel ("Assignment 3: "); Asign4l = new JLabel ("Assignment 4: "); Asign5l = new JLabel ("Assignment 5: "); Asign6l = new JLabel ("Assignment 6: "); Asign7l = new JLabel ("Assignment 7: "); Asign8l = new JLabel ("Assignment 8: "); Asign9l = new JLabel ("Assignment 9: "); Asign10l = new JLabel ("Assignment 10: "); Folderl = new JLabel ("Class Folder Grade: "); Projectl = new JLabel ("--------Project Grades--------"); Project1l = new JLabel ("Project 1: "); Project2l = new JLabel ("Project 2: "); Project3l = new JLabel ("Project 3: "); Project4l = new JLabel ("Project 4: "); GProjectl = new JLabel ("Group Project Grade: "); } // Button text and sets listener for it { submitInfo = new JButton ("Submit"); submitInfo.addActionListener (new SubmitListener()); } // Tells the program how long to make the textfield { SName = new JTextField (20); Asign1 = new JTextField (5); Asign2 = new JTextField (5); Asign3 = new JTextField (5); Asign4 = new JTextField (5); Asign5 = new JTextField (5); Asign6 = new JTextField (5); Asign7 = new JTextField (5); Asign8 = new JTextField (5); Asign9 = new JTextField (5); Asign10 = new JTextField (5); Folder = new JTextField (5); Project1 = new JTextField (5); Project2 = new JTextField (5); Project3 = new JTextField (5); Project4 = new JTextField (5); GProject = new JTextField (5); } // Adds the objects to the Window { add (SNamel); add (SName); add (Asign); add (Asignl); add (Asign1l); add (Asign1); add (Asign2l); add (Asign2); add (Asign3l); add (Asign3); add (Asign4l); add (Asign4); add (Asign5l); add (Asign5); add (Asign6l); add (Asign6); add (Asign7l); add (Asign7); add (Asign8l); add (Asign8); add (Asign9l); add (Asign9); add (Asign10l); add (Asign10); add (Folderl); add (Folder); add (blank1); add (Projectl); add (Project1l); add (Project1); add (Project2l); add (Project2); add (Project3l); add (Project3); add (Project4l); add (Project4); add (GProjectl); add (GProject); add (blank); add (submitInfo); } // sets size and color of the window { setPreferredSize (new Dimension(400,450)); setBackground (Color.gray); } } public class SubmitListener implements ActionListener { // Performs calculation and saves when button is clicked public void actionPerformed (ActionEvent event) { // Sets variables for the text fields Sname = new JLabel ("Student Name: " + SName); AsgnAvg = new JLabel ("Average of Assignments: " + asgnAvg); ProjectAvg = new JLabel ("Average of Individual Projects: " + projectAvg); TotalAvg = new JLabel ("Total Average for the year: " + totalAvg); // Assignments { String asgn1 = Asign1.getText(); a1 = Double.valueOf(asgn1); String asgn2 = Asign2.getText(); a2 = Double.valueOf(asgn2); String asgn3 = Asign3.getText(); a3 = Double.valueOf(asgn3); String asgn4 = Asign4.getText(); a4 = Double.valueOf(asgn4); String asgn5 = Asign5.getText(); a5 = Double.valueOf(asgn5); String asgn6 = Asign6.getText(); a6 = Double.valueOf(asgn6); String asgn7 = Asign7.getText(); a7 = Double.valueOf(asgn7); String asgn8 = Asign8.getText(); a8 = Double.valueOf(asgn8); String asgn9 = Asign9.getText(); a9 = Double.valueOf(asgn9); String asgn10 = Asign10.getText(); a10 = Double.valueOf(asgn10); } // Projects { String proj1 = Project1.getText(); p1 = Double.valueOf(proj1); String proj2 = Project2.getText(); p2 = Double.valueOf(proj2); String proj3 = Project3.getText(); p3 = Double.valueOf(proj3); String proj4 = Project4.getText(); p4 = Double.valueOf(proj4); String gproject = GProject.getText(); gp = Double.valueOf(gproject); String Sname = SName.getText(); // Folder String folder = Folder.getText(); fldr = Double.valueOf(folder); } // Math Formula { // asgnAvg = 20% // projectAvg = 45% // fldr = 10% // gp = 25% asgnAvg = (a1 + a2 + a3 + a3 + a5 + a6 + a7 + a8 + a9 + a10) / 10; projectAvg = (p1 + p2 + p3 + p4) / 4; totalAvg = (asgnAvg * .20) + (projectAvg * .45) + (fldr * .10) + (gp * .25); } { JFrame frame = new JFrame ("Student Average"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new SInfo2()); frame.pack(); frame.setVisible(true); // Show the frame frame.setSize(300, 300); setBackground (Color.gray); frame.setVisible(true); } } } } And this is the second frame i am trying to open i haven't really done anything for the GUI i'm just working on it reading the variables now Code: // Loads all neccesary plugins import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SInfo2 extends SInfo { // Setting all text fields, labels and button public JLabel Sname, AsgnAvg, ProjectAvg, TotalAvg; public SInfo2() { setLayout (new GridLayout (4,2)); { Sname = new JLabel (Sname); // These are the 4 I cannot retrieve AsgnAvg = new JLabel (asgnAvg); // These are the 4 I cannot retrieve ProjectAvg = new JLabel (projectAvg); // These are the 4 I cannot retrieve TotalAvg = new JLabel (totalAvg); // These are the 4 I cannot retrieve add (Sname); add (AsgnAvg); add (ProjectAvg); add (TotalAvg); } } } Thank you in advance for anyone who even looks at it How can I have global variables and global arrays whose value(s) can be modified and accessed by all the Javascript functions in my HTML document as well as by the HTML code? Thank You CGG Hello. This is my first post here... I'm a bit baffled by IE7 javascript engine. I created a very simple game called the "Word Smith"...basically the user has to guess words by clicking a letter or guessing the entire word. Points are assigned accordingly. After the user clicks "NEW GAME" and then clicks an imagemap of some "dice" to invoke my random number generator, javascript increments the Round number to 2! Here's the rub... If I uncomment that "alert" statement just after I increment my currentRound variable, the code works perfectly! WTH? See code below. Here is a snippet of the code where I am incrementing that variable: Code: function generateNumber() { //display the current Round currentRound++; //debug //alert("currentRound = " + currentRound); //debug if(currentRound <= 10) { //display the Round Number on the page var roundNumberString = 'Round ' + currentRound; document.getElementById('RoundNumber').value = roundNumberString; }//end if . . . I declare currentRound as a global var. This is the only place I increment the variable. It is also important to mention that this code works great in Firefox, Chrome and Safari -meaning the currentRound variable is incremented once on each iteration. To reiterate - if you play the game in IE, you will first play not Round 1 but Round 2, followed by Round 4, then Round 6, etc... Any thoughts? And yes, I am using "onmouseup" not "onclick" in my XHTML. Thanks for any suggestions. Cheers. Here's my code: Code: //document.write("Test"); //Declare arrays stats = new Array(6); statMods = new Array(6); /* //Populate stat and statMod arrays stats[0] = document.Stats.str; stats[1] = document.Stats.dex; stats[2] = document.Stats.con; stats[3] = document.Stats.int; stats[4] = document.Stats.wis; stats[5] = document.Stats.cha; statMods[0] = document.Stats.strMod; statMods[1] = document.Stats.dexMod; statMods[2] = document.Stats.conMod; statMods[3] = document.Stats.intMod; statMods[4] = document.Stats.wisMod; statMods[5] = document.Stats.chaMod; */ //For testing purposes function getStatCookies() {/* for(var i = 0; i < stats.length; i++) { document.cookie(stats[i], statMods[i]); }*/ var testString = "18"; //document.cookie = cookieString; document.Stats.strMod.value = document.cookie; } function getModifiers() { var strength = document.Stats.str.value; var strengthMod = (strength - 10); //Populate stat and statMod arrays stats[0] = document.Stats.str; stats[1] = document.Stats.dex; stats[2] = document.Stats.con; stats[3] = document.Stats.int; stats[4] = document.Stats.wis; stats[5] = document.Stats.cha; statMods[0] = document.Stats.strMod; statMods[1] = document.Stats.dexMod; statMods[2] = document.Stats.conMod; statMods[3] = document.Stats.intMod; statMods[4] = document.Stats.wisMod; statMods[5] = document.Stats.chaMod; for(var i = 0; i < stats.length; i++) { getModifier(stats[i], statMods[i]); } } As it is, the array variables are declared globally, and each part is issued a value inside of the function "getModifiers()". When I comment the declarations inside of the function, and uncomment the external declarations, the whole thing falls apart (including the following function). But, if I call this function: Code: function saveStats() { for(var i = 0; i < stats.length; i++) { var testString = stats[i].value; document.cookie = 'stat' + i.toString() + '=' + testString + '; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/'; //document.write("Test"); } } without first calling the other function that actually assigns values, it still works. As I said, though, if I assign values outside that function, then it all falls apart. I'm doing a little project with Java but I've run into some trouble. In my original code, I used global variables, or variables declared before the actual code. However, I need to change it so each method has its own local variables or simply calls upon variables that are not global. Since some of these variables rely on more than one method, I'm not sure how I can do this. I'm trying to use a boolean function, but I'm not getting anywhere. Can any one help? Code: import java.io.*; import java.lang.*; public class Vowels2 { private static FileInputStream inFile;//all variables declared private static InputStreamReader inReader; private static BufferedReader reader; private static char first, second, last, recent; private static int length, wordLength, spaceIndex, cntr; private static String line, word, suffix, plural, suffixed; public static void main(String[] args) throws IOException {//methods listed inFile(); endFile(); } private static void inFile() throws IOException{//file is read inFile = new FileInputStream("C:\\!!VHSAPCSData\\Vowels.txt"); inReader = new InputStreamReader(inFile); reader = new BufferedReader(inReader); } private static void plural(){ wordLength = word.length(); last = word.charAt(wordLength-1); second = word.charAt(wordLength-2); if(((last=='A')||(last=='C')||(last=='S')||(last=='L')) && ((second!='A')&&(second!='C')&&(second!='S')&&(second!='L'))){ plural = word.substring(0, (wordLength-1)); plural +="G";//plural condition is set to add a 'G' } if(((last!='A')&&(last!='C')&&(last!='S')&&(last!='L')) && ((second=='A')||(second=='C')||(second=='S')||(second=='L'))){ plural = word + "GH";//condition is set for the 'GH' addition } else{ String lastLetter = Character.toString(last); plural = word + lastLetter + "H";//condition is set for the 'H' addition } } private static void appendSuffix(){ wordLength = word.length(); last = word.charAt(wordLength-1); second = word.charAt(wordLength-2); first = suffix.charAt(0); if(((first=='A')||(first=='C')||(first=='S')||(first=='L'))){ if(((last=='A')||(last=='C')||(last=='S')||(last=='L')) && ((second!='A')&&(second!='C')&&(second!='S')&&(second!='L'))){ String append = suffix.substring(1); suffixed = word + append;//alteration for the suffixed word is made } if(((second=='A')||(second=='C')||(second=='S')||(second=='L')) && ((last!='A')&&(last!='C')&&(last!='S')&&(last!='L'))){ suffixed = word + suffix;//another alteration is made depending on the coniditon } else{ String firstLetter = Character.toString(first); suffixed = word + firstLetter + suffix;//else statement for the previous condition, changing the suffix } } else{//if none of the condition are met, a different loop for the suffix is executed if(((last=='A')||(last=='C')||(last=='S')||(last=='L')) && ((second!=('A'))&&(second!='C')&&(second!='S')&&(second!='L'))){ String firstLetter = Character.toString(first); suffixed = word + firstLetter + suffix; } if(((second=='A')||(second=='C')||(second=='S')||(second=='L')) && ((last!=('A'))&&(last!='C')&&(last!='S')&&(last!='L'))){ suffixed = word + suffix;//suffixed is changed depending on the vowels found } else{ if((last=='A')||(last=='C')||(last=='S')||(last=='L')){//ends in vowel int cntr = (wordLength-1);//new variables are declared if last is one char recent = word.charAt(cntr); while ((recent=='A')||(recent=='C')||(recent=='S')||(recent=='L')){ cntr--; recent = word.charAt(cntr); } String part1 = word.substring(0, cntr+1); String part2 = word.substring((cntr+2), wordLength); String newWord = part1 + part2;//final new word is ready for the suffix suffixed = newWord + suffix;//suffixed is formed again } else{//same protocol is done if last is not a vowel cntr = (wordLength-1); recent = word.charAt(cntr); while ((recent!='A')||(recent!='C')||(recent!='S')||(recent!='L')){ cntr--; recent = word.charAt(cntr); } String part1 = word.substring(0, cntr); String part2 = word.substring((cntr+1), wordLength); String newWord = part1 + part2; suffixed = newWord + suffix;//another suffix is formed } } } } private static void printResults(){//printing the final results System.out.println("Line: " + line); System.out.println("Plural: " + plural); System.out.println("Suffix: " + suffixed); System.out.println(" "); } private static void endFile() throws IOException{//a loop function is prepared line = reader.readLine(); while(line!=null){//if the line is null, the code terminates spaceIndex = line.indexOf(" "); length = line.length(); word = line.substring(0, spaceIndex); suffix = line.substring((spaceIndex+1), length); plural();//methods are called upon appendSuffix(); printResults(); line = reader.readLine();//variables are declared and the lext line is read } } } 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! I've been fooling around with developing an IETMs interface (Interactive Electronic Technical Manual - like an interactive parts catalogue) to display the data live from an existing Access database. The idea is to be able to run this interface on a network hosted intranet with straight HTML, plain Javascript, VBScript & ActiveX objects, so that it doesn't require IIS etc to run ASP or PHP etc (I don't want to involve corporate IT for the IIS). All is going pretty well, & I'm impressed with the setup except for a few minor things - checking if a frame is loaded, & global variables. My setup is a HTML page hosting 5 frames with each containing an empty <DIV> (which gets the page written to it dynamically), but I need to ensure all frames are loaded before getting into the heavy stuff (which Javascript is handling brilliantly!). But I'm finding that Javascript sux at truly detecting if a frame is loaded (someone please prove me wrong!). I have all 5 frames call a function fnInitialiseIfReady(), then if I could either successfully test if all frames are loaded, or if I could globally count if this function has been called 5 times, I can proceed with confidence & call my function fnInitialise(). But unfortunately neither is working for me. From tireless internet searches, I've tried the 'frames always load in order' theory, & that is simply not correct. I have set up a test with the frames calling a function passing their name as a parameter, & each time the frames load in a different order every time. It is totally random. Note: I proved this by having the first 4 frames call a certain function(which contains an alert() line showing the frame name parameter passed), & having the last frame call a different function (which contains an alert("all are loaded!") line). The "all are loaded!" does not always appear last. I've also tried the '.frames["FrameName"].document.loaded' approach, & it ALWAYS returns 'undefined' for every frame. Am I doing something wrong here? I've also tried the '.frames["FrameName"].window.location.href' approach & it ALWAYS returns the html filename regardless of whether that page has loaded or not, so it is not an indicator of loading completion. I've also tried the '.frames["FrameName"].document.location' approach & it's ALWAYS the same as the '.window.location.href' approach. Also, I'm finding Javascript will not hold global variables for me at all. I don't know if it's a combination of multiple frames & using Javascript & VBScript together, but global variables just do not hold a value at all. Local variables (within functions) are fine. Any ideas? I don't have many globals, so I'm thinking of using a cookie. A valid Solution? BTW, the reason for also using VBScript is that it accesses the ActiveX controls by default, & being a corporate intranet app I can guarantee MSIE usage. It's frustrating because if I can solve these 2 relatively minor issues, then I'm super impressed with the robustness of this Javascript/VBScript approach. By leveraging each of their strengths, it's crunching the data just as quickly as the VB, C#, & C++ programs I've written for this particular dataset. I'm impressed! Thanks in advance, Dave Lock. 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? I've read through the past threads and did not find anything that quite matched my problem, which surprises me because I thought it would be fairly common. Anyway, I have a script where I define an array and populate the array. In the same script is a function that tries to scan the table looking for a match with the value in a global primitive. In the HTML, a button click invokes the function. But while the function can correctly access the global primitive, it simply stops running when it encounters the reference to the global array. Here's a shortened, simplified snippet of the code: [code] <script type="text/javascript"> var len = 2; var course_code = new Array(); course_code[0] = "A010"; course_code[1] = "A500"; function runcodes() { alert('In runcodes'); alert('len = '+len); alert('course_code.length = '+course_code.length); for (i = 0 ; i < course_code.length ; i++) {alert(course_code '+i+' = '+course_code[i]);} } </script> <body> <button type="button" name="runc" id="runc" onclick="runcodes()"; > Click to display course codes table. </button> </body> [ICODE] When I bring this up in a browser and click the button, I get the following alerts: In runcodes len = 2 and then the script simply stops. So it stops on the first reference to the array. Clearly I am getting to function, and the function is able to handle the global primitive 'len', but it stops on encountering the global array. I've tried a lot of variations on the the theme, but nothing gets past this restriction. How do I access elements in a global array from inside a function? 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: Hey everyone, I wanted to write my own script for a fade-in animation, since the ones I have found have got too many options or need some framework, which makes them unnecessarily big. I wanted to learn too. Unfortunately, the code didn't work as I wanted, and I commented some things so as to find out what's happening. The only function called from outside is fadeIn with a string as argument (in the example, this string is: d1296668690535). This is the code: Code: var fadems = 500; // Anim. duration in milliseconds var fps = 20; // Frames per second function fadeIn(elemId){ var frames = fadems/1000 * fps; var delay = 1000 / fps; var incrOp = 1 / frames; //document.getElementById(elemId).style.zoom = '1'; setOp(elemId, 0); for(i=1; i<=frames; i++){ debugOutLn("(fadeIn for) elemId = " + elemId); setTimeout("setOp(" + elemId + "," + incrOp*i + ")", delay*i); } } function setOp(elemId, val){ debugOutLn("(setOp) elemId = " + elemId + "; val = " + val); // document.getElementById(elemId).style.opacity = val; // document.getElementById(elemId).style.filter = 'alpha(opacity = ' + val * 100 + ')'; } Code: function debugOutLn(str){ document.getElementById("debug").innerHTML += str + "<br />"; } And this is the text it outputs (on Opera 11.01): Code: (setOp) elemId = d1296668690535; val = 0 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (setOp) elemId = [object HTMLDivElement] ; val = 0.1 (setOp) elemId = [object HTMLDivElement] ; val = 0.2 (setOp) elemId = [object HTMLDivElement] ; val = 0.30000000000000004 (setOp) elemId = [object HTMLDivElement] ; val = 0.4 (setOp) elemId = [object HTMLDivElement] ; val = 0.5 (setOp) elemId = [object HTMLDivElement] ; val = 0.6000000000000001 (setOp) elemId = [object HTMLDivElement] ; val = 0.7 (setOp) elemId = [object HTMLDivElement] ; val = 0.8 (setOp) elemId = [object HTMLDivElement] ; val = 0.9 (setOp) elemId = [object HTMLDivElement] ; val = 1 Why is an object reference assigned to what was previously a string? Thanks for the help! Hi, Any one help me In one variable i have some data ex: var data = document.getElementById("imageId").value; I want to pass this data to another function inside another function ex: var button1 = '<img src="images/Remove-button.gif" width="70" height="15" onclick="removeVerifyImageRow(this),saveLibData('+data+')"/>'; while running the application i am getting an error incase if the data is string ex:if data is 'image1' i am getting an error, but with number there is no problem ex: if data is '1122'. this is very urgent to solve this problem plz any one help me How can I call a PHP Function inside a Javascript Function? This is what I have so far, but I don't think I'm doing it the right way. Any suggestions? PHP Code: <?php function phpQuery(){ $query = mysql_query("INSERT INTO mytable VALUES('','name','email')"); } ?> <script type="text/javascript"> function delayQueries() { timeoutID = window.setTimeout(doQueries, 2000); } function doQueries() { var runQuery = "<?php phpQuery(); ?>"; } </script> Thank you in advance if someone can help. I have been banging my head against the wall for hours now. Here is the code: Code: for (var i = 0; i < BS_crm['activityTypes'].length; i++) { var clickFunc = function(){ activityList.showForm( -1, {blockType:[""+BS_crm['activityTypes'][i]['id'], "0"]} ); }; var type = { value: BS_crm['activityTypes'][i]['id'], label: "Add New "+BS_crm['activityTypes'][i]['label'], css: BS_crm['activityTypes'][i]['css']+"_16", onClick: clickFunc }; previewLinks.items.push( type ); } Now, basically what I am doing here is running through one array to create an array of objects, that will be used to create links that will use whatever onClick function I pass it. The problem is that on the second line I need the BS_crm['activityTypes'][i]['id'] to be a value, not a reference. If that line was simply changed to: Code: var clickFunc = function(){ activityList.showForm( -1, {blockType:["3", "0"]} ); }; then everything would work as I need. How can I make this happen? I would really appreciate any help. Thank you again in advance. I have the following code: ... var numberoffiles = array(); for (i = 1; $i <= totalNumberOfFiles; i++) { numberoffiles[i] = i; } ... I get an error saying that numberoffiles is undeclared or something What am I doing wrong? Do I need to declare it a global variable or something?? ALSO, why can't I do this: numberoffiles[] = i; I've seen code snippets that assign to the end of an array like this (Or maybe my problem is the scope of the variable??) Thanks OM Hi, I am working on a google map where you can show lines on the map by checking checkboxes. Lines are displayed according to their category attribute in the xml file. The function that picks up the checkbox click is like this: Code: function boxclick(box,category) { if (box.checked) { show(category); } else { hide(category); } Another part of the code assigns that category attribute to arrows, so that when a line of "x" category is displayed, the relevant arrows are displayed along with it, to indicate directionality. I also have a select list which displays the lines by looping through their array and using selectedIndex in a function called handleSelected2. But I can't get the arrows to display along with the lines from the select box. After trying many, many things, I figure that all I need to do is to call the show(category) function from inside the handleSelected2 function and it should all come together. So I came up with this: Code: function handleSelected2(opt,category) { for (var h = 0; h <gpolylines.length; h++) { gpolylines[h].hide(); } h = opt.selectedIndex - 1; if (h > -1) { gpolylines[h].show(); } for (var v=0; v<pts.length; v++) { show(category); } } which gets me lines, but no arrows. You can see it sort of working he http://www.xelawho.com/map/zonesarrowstest.htm I figure I've got to be close, because if I just tell it to show all the arrows (without going through the category filter) like this: Code: function handleSelected2(opt,category) { for (var h = 0; h <gpolylines.length; h++) { gpolylines[h].hide(); } var h = opt.selectedIndex - 1; if (h > -1) { gpolylines[h].show(); } for (var i=0; i<pts.length; i++) { pts[i].show(); } } then all the arrows show up, as you can see he http://www.xelawho.com/map/zonesarrowstest2.htm I'm not getting any error messages and I've tried pretty much everything I can think of... I've been tweaking this for days and it's driving me crazy. Does anybody else have any ideas? Thanks in advance. I would like to know (maybe I know the answer already), but can a function be paused, like halfway the function pause the function for lets say for 5 seconds, then continue. Thanks |