JavaScript - Incrementing Global Variables
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. Similar TutorialsOk 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 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. 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 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 } } } 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> 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. This works: Code: <div id="oDiv" style="width:300;height:100;background-color:#000000;"></div> <a href="#" onclick="getHght('exp');">Expand</a> <a href="#" onclick="getHght('con');">Contract</a> <script type="text/javascript"> <!-- function getHght(act){ var doc = document.getElementById("oDiv"); if (act == "exp"){ doc.style.height = 300 ; } else if (act == "con"){ doc.style.height = 100 ; } } //--> </script> This is exhibits the desired functionality, but it doesn't work: Code: <div id="oDiv" style="width:300;height:100;background-color:#000000;"></div> <a href="#" onclick="getHght('exp');">Expand</a> <a href="#" onclick="getHght('con');">Contract</a> <script type="text/javascript"> <!-- function getHght(act){ var doc = document.getElementById("oDiv"); if (act == "exp"){ doc.style.height += 30 ; } else if (act == "con"){ doc.style.height -= 30 ; } } //--> </script> IE give an "invalid argument" error. No error in FF. I had the same [failed] result using .getAttribute(), and .setAttribute(). How should I approach this? -james Novice Javasript query. My requirement: Each time a visitor arrives at a specific webpage i want the main image on the page to be different, or more specifically, one of 6 images which will be shown in rotation. Solution: Set a cookie. Each time the visitor access the page read the cookie and display the corresponding image. Then increment the value and rewrite the cookie, so that next time they'll see the next image in sequence. NB: if the cookie does not exist (first timer) or is at 6, then the value is set to zero (and then incremented). Problem: Can't get my coding to work. Specifically it just doesn't do anything - no error message, no cookie written. I'm a very novice scripter, as in I've cobbled the coding together from bits off the net that i think i've managed to grasp some kind of an understanding of. Very suck it and see - so far lots of sucking and no seeing! Anyway here's my code - if someone could cast a beady eye it would be much appreciated. Hopefully I'm not a million miles out !!! Code: <script type="text/javascript"> /*<![CDATA[*/ var cookies = document.cookie; if (cookies.indexOf(pookie) == -1) { var pookey = 0; } else { var startpos = cookies.indexOf(name)+name.length+1; var endpos = cookies.indexOf(";",startpos)-1; if (endpos == -2) endpos = cookies.length; var pookey = cookies.substring(startpos,endpos); if (pookey == 6) pookey = 0; } pookey = pookey++; var expire = new Date (); expire.setTime(expire.getTime() + 1000 * 60 * 60 * 24 * 365); document.cookie = name + "=" + pookie + "; expires=" + expires.toGMTString() + "; path=/"; if (pookey == 1) document.write ("<img src=\"../HomePage/Image1.jpg\" />"); if (pookey == 2) document.write ("<img src=\"../HomePage/Image2.jpg\" />"); if (pookey == 3) document.write ("<img src=\"../HomePage/Image3.jpg\" />"); if (pookey == 4) document.write ("<img src=\"../HomePage/Image4.jpg\" />"); if (pookey == 5) document.write ("<img src=\"../HomePage/Image5.jpg\" />"); if (pookey == 6) document.write ("<img src=\"../HomePage/Image6.jpg\" />"); /*]]>*/ </script> Thanks in advance for any help... Simply put, I need to take a variable (The number '20' in this case) that is displayed by an input box on my web page and plug it into a function so that whenever I click on a button, the number in the input box will decrease by 1. Seems simple enough, though for hours I've been going at it with no luck. Skipping the rest of my code - I currently have: Code: <head> <title> Online Slots </title> <script type="text/javascript" src="http://dave-reed.com/book/random.js"> </script> <script type="text/javascript"> function DoSpin() { var count; count = 20 document.getElementById("countBox") = count - 1; } </script> </head> <body> <div style="text-align:center"> <input type="button" value="Click to Spin" onclick="DoSpin()" /> <br /><br /> Current Funds: <input type="text" id="countBox" size="4" value="20" onfocus="blur();" /> </div> </body> The entire code is a slot machine project that's supposed to be extremely simple where you hit the button and it spins 3 wheels, 3 of the same image and you win. Every spin takes $1, every win gives $13. The majority of the code is already working, however for some reason I appear to be failing badly at getting the read out to show a decrement of $1 every time you push the button. I know this is a bit newbie of a question to be asking; but I've tried so many different ideas that I've found across w3schools, webdevelopersnotes, dave-reed, ect - and so far I haven't been able to get any of them to work correctly. Any help would be great! Hi all, working on building a website at the moment. and i need to create a script that will increment a number by 0.01, then stop and decrease by 0.03, then increase again by one. I wrote code to increment by 0.01 continuouly but now i can't stop it. and change to decreasing <script type = "text/javascript"> num = 0.87; var tim = 0; function makeNum() { num = ((num*1) + .01).toFixed(2); document.getElementById('count').innerHTML = num-.01; tim = window.setTimeout("makeNum()", 2000); } makeNum(); </script> And now I'm Completly stuck. Help would be grately appreciated Thanks hello I want ask how can i declare global variable in html file , and use it in java script file . - with same value- thanks Hello, I am trying to make an example that will change when a user selects options. Like: This is some text. <user checks box to remove "some"> This is text. <user checks box to remove "text"> This is. <user UN-checks box to remove "text"> This is text. The problem is, if I try to add the removed text back, I get the original string, even though it was previously changed. I use to have the string between the <p> tags, but then moved it as a global var in the JS file. Code: /* HTML Code */ <body> <input type="checkbox" id="anoption" /> <p id="exampletext"></p> //Text use to be here </body> /* Javascript code(including jquery) */ var example = "This is some text"; //Global in JS file $('document').ready(function(){ $('#exampletext').text(example); //Place the global var in the html }); $('#anoption').click(function() { //Place a click handler for checkbox var tmp = example; if(tmp.search(/some/)) //Attempting to check if the word is there, i don't think this works right { example = tmp.replace("some", ""); } else // if word is not there - add it back { /* Here is where I could also use some logic help. I tried a few things here. */ } I am not sure if using a string is the best way or not. Could anyone please point me in the right direction? Thank you! Hello. Using the Firebug console is there a way to log the content of the global namespace? I particularly want to recognise when something is added to it by my code. I could step through my whole code but I'm hoping there is an easier way. Andy. 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. Could someone please change this line so that it respects the global namespace: Code: var selected = students.options[students.selectedIndex].value; The error console is telling me to use document.getElementById but I don't know where to put it. Thanks. I want to configure ctrl+shift+z as a shortcut for an action in my page. But the key combination is already a global shortcut for my music player. Can i override the global shortcut or prevent the global shortcut action or just intimate the user that a global shortcut already exists for the key combination 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? 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, 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 |