JavaScript - Global Variables In Javascript
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 Similar TutorialsI'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. 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 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. 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. 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 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 Hi, 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> Hi, I have the following code snippet: test.html ====== <script language="javascript" type="text/javascript"> var testVariable = "test"; </script> <script language="javascript" type="text/javascript" src="test.js"> </script> test.js ===== var testVariable = window.top.testVariable; In firefox, I'm able to access testvariable defined within test.html in test.js. But in chrome, test.js couldnot get the window.top.testVariable field defined in test.html. Can any one please let me know how i can make it work in chrome?. Am i missing something here?. All -- I have a JavaScript config file called gameSetting.js which contains a bunch of variables which configures a particular game. I also have a shared JavaScript library which uses the variables in gameSetting.js, which I include like so: <script type="text/javascript" src="gameSetting.js" ></script> <script type="text/javascript" src="gameLibrary.js" ></script> In gameSetting.js I have: $(document).ready(function() { // call some functions / classes in gameLibrary.js } in Firefox, Safari, and Chrome, this works fine. However, in IE, when it's parsing gameSetting.js, it complains that the functions that live in gameLibrary.js aren't defined. When it gets to parsing gameLibrary.js, the variables in gameSetting.js are reported as not being defined. I've tried dynamically bootstrapping the gameLibrary file using this function in document.ready for dynamic load... $.getScript("gameLibrary.js"); However, the same problem still happens in IE, where when it parses the files individually it's not taking into context the file/variables that came before, so it's not an out of load order problem. My options a 1) collapsing all the functions in gameLibrary.js and variables in gameSetting.js into one file. However, this is not practical because this is dealing with literally hundreds of games, and having a gameLibrary.js in ONE location for ONE update is what makes most logical sense. 2) figure out a way to get this to work where variables in file1 are accessible to file2 in IE (as it seems they are in other browsers). jQuery seems to be able to have multiple plugins that all refer to the based jQuery-1.3.2.js, so I know there is a way to get this to work. Help appreciated. Nero Hi, I'm looking to use the document function in javascript to change the TYPE of an INPUT. However I want to change the TYPE of the INPUT according to a variable passed to the javascript button, so i use: document.formname.inputname.value="newvalue"; I want to be able to change what inputname is depending on what is passed to the function, but right now firefox is telling me that it's undefined. Is there any way I can do this? Thanks in advance, Daniel I am perplexed about this one. Not sure if php is the best solution or maybe javascript. ( or both.) I am writing a litle script that will go to my mysql table and take out 20 rows ( from about 10,000 rows ) based on the WHERE statement. Then I want to step through these 20 rows displaying just two filds in this fashion: First, I want to display one field in a "box" ( using divs and css ) then wait for a form input. Then while keeping the first displayed box and field display the second field in a similar box a fee lines below. Wait for a form input update some data. Then onto the next row. If I use javascript then I could keep all the processing on one page and not have to have server refreshes. But how do I get these those array elements from $row['field1'] and $row['field2'] into javascript vars ? Is this the best way to do this ? Or would php and having a couple of extra trips to the server for form processing be better ? Thanks for any input. . Hi, Ive got a iphone based website im writing in html/javascript, it all works perfectly well apart from an issue with a javascript variable and i cant figure out what im doing wrong At the start of the code i declare a variable var jpgname='blank'; - its blank for testing I then have a href which attempts to change this variables value when clicked <li class="flip"><a onClick="jpgname='test'" href="#page">Cars</a></li> If i replace the jpgname='test' with confirm('test) i get a popupbox so i know its running this code under my #page section (just a div named section) i have [<h1><script>document.write(jpgname);</script></h1> however this always has the value 'blank' Im sure im doing something stupid but im not sure what Any help gratefully recieved thanks Mike Hi, I hope someone can help me! I have a list of buttons, each with a different id which is taken from the ids of these values from the database. When I click one of the buttons it shows the items that correspond to this id in the database. Therefore, when different buttons are clicked the display changes to match the objects relating to this particular button. When a button is clicked, this shows various other objects which I can then select (using a checkbox). When a checkbox is clicked, a Javascript function is called to change the html text next to the appropriate button. However, I can't get this to work as I need to pass the id of the button, and the html span, to the Javascript in order to change the correct text. Here is my Javascript : Code: function questionnum(checkbox) { if(checkbox.checked) { var qdesNumElement = document.getElementById('<?php echo $q;?>'); var qdesNum = qdesNumElement.innerHTML; qdesNumElement.innerHTML = ++qdesNum; } This code only gets the last button. Please help. I have jQuery like: jQuery(".forms_1_1").validate({ rules: { inputname1: { required: true, }, or inputname1: { required: "Requested field!.", }, Is it technically possible to add 1. PHP variable like $_SESSION and 2. Smarty variable into Javascript like {$global.variable1} inputname1 is value for each variable (PHP, Smarty). Need help how to include variable values into Javascript code. Hi all, I'm a javascript newbie and having some trouble with what I imagine it s a very basic issue! I am trying to declare a variable inside a function and use it later on in my code... but it just already returns white space... i.e. not variable value. I am setting it within this function: Code: function show_video1(){ document.getElementById('video1').style.display="block"; var video1Name = "Education World News (Part 1)"; document.getElementById('video2').style.display="none"; document.getElementById('video3').style.display="none"; document.getElementById('video4').style.display="none"; document.getElementById('video5').style.display="none"; document.getElementById('video6').style.display="none"; document.getElementById('video7').style.display="none"; document.getElementById('video8').style.display="none"; document.getElementById('video9').style.display="none"; document.getElementById('video10').style.display="none"; document.getElementById('video11').style.display="none"; } and trying to call it later on with this: Code: <script type="text/javascript">document.write(video1Name)</script> It might be worth noting that each one of my 11 videos will hace a different name. Can anyone help out a newbie? Many thanks, greens85 Hi, I am using javascript to collect hidden form elements and then send the values to a php page, without reloading or changing the page. Basically i have a list of job vacancies, with just an apply button, when a person clicks on the apply button, the form collects some information from their account and sends it using the javascript code. Now this works fine, except for if somebody then clicks on the second job it sends the information from the first form again. And it seems to remember the information. What i am trying to find out is it possible to have multiple forms on one page which once submitted send variables to javascript which then send them to a php but clear themselves so that it doesn't remember the previous values. Here is the code for the form: Code: <form id="submit" method="post"> <fieldset> <input type="hidden" name="usern" id="usern" value="php variable" /> <input type="hidden" name="joborder_id" id ="joborder_id" value="php variable" /> <input type="hidden" name="site_id" id ="site_id" value="php variable" /> <button class="button positive">Apply For This Job </button> </fieldset> </form> <div class="success" style="display: none;">Your Application has been sent.</div> </form> And the Javascript code is he Code: $(document).ready(function(){ $("form#submit").submit(function() { // we want to store the values from the form input box, then send via ajax below var usern = $('#usern').attr('value'); var joborder_id = $('#joborder_id').attr('value'); var site_id = $('#site_id').attr('value'); $.ajax({ type: "POST", url: "apply.php", data: "usern="+ usern +"& joborder_id="+ joborder_id +"& site_id="+ site_id, success: function(){ $('form#submit').hide(function(){$('div.success').fadeIn();}); } }); return false; }); }); Any ideas or suggestions would be appreciated, Thanks Lee Hi, in PHP I can assign a variable do... PHP Code: function setvar($anyvar,$val){ $$anyvar=$val; } setval('myvar',$whatever); how to do in javascript ... I thied window.anyvar= and this[anyvar] and several other combinations but no joy Edit: fixed, my bad, was being a muppet, was calling setvar(varname,val) instead of setvar('varname',val); I am about to translate some C++ code to JavaScript. In C++, it is straightforward to declare and use a Boolean variable; all I do is swap it between true and false and back again as needed. For example, Code: // C++ Code . . . bool na = 1; . . . na = !na; . . . I am wondering if JavaScript offers boolean variables. As far as I know, it does not, but I thought I would confirm by asking around. At the moment, I am planning to code the comparable block in Javascript using an "if" statement or a ternary operation. For example, Code: JavaScript Code . . . var na = 1; // Option 1 if (na) na = 0; else na = 1; // Option 2 na = ((na) ? 0 : 1); . . . Is one of these options recommended as the best way to simulate a boolean variable and operation? (I would like the fastest-executing code possible.) Or is there another--better--way to do it? All advice and recommendations appreciated. Thank-you in advance. |