JavaScript - Help Assigning New Value To Global Variable.
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. Similar TutorialsI 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? hello I want ask how can i declare global variable in html file , and use it in java script file . - with same value- thanks 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 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> 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 all! Got a question I can't seem to find an answer to. I have a little JS app that is a glorified calculator which I posted the code for below. My code uses the document object to replace the html in the "content" <div> and works great. However, I want to add an inline style in order to change the background of the input (readonly field with an id of "coutput") based on either of the global variables named "MJPD" or "IJPD", (depending on the switch case selected in the user prompt at the beginning of the script.) Simplified....if the value of MJPD is less than 4.6, I want the "coutput" field's background to be red, else be green. The same goes for IJPD, except the threshold for red will be <3.83. Code and what I have tried is below. After reading the code, look below it to see what I have tried and maybe tell me what I'm doing wrong! =) Any help is greatly appreciated.......I have spent a week searching for this little answer and I can't seem to find it! Code: <script language="JavaScript"> var MJPD = 1; var IJPD = 1; function sayhello(){ // *** live test for inline JS code placement alert("IT WORKS!!! Now change me =)"); } ////////////////////////////////////////////////////// function changeScreenSize(w,h) { window.resizeTo( w,h ) } /////////////////////////////////////////////////// function iJPDCalc(form) //calculate IJPD value { var ij = parseFloat(form.IJobs.value, 10); var it = parseFloat(form.ITime.value, 10); var IJPD = 0; IJPD = (ij / it) * 8.0; form.I_JPD.value = IJPD; } ///////////////////////////////////////////////////// function mJPDCalc(form) //calculate MJPD value { var mj = parseFloat(form.MJobs.value, 10); var mt = parseFloat(form.MTime.value, 10); var MJPD = 0; MJPD = (mj / mt) * 8.0; form.M_JPD.value = MJPD; } ///////////////////////////////////////////////////// function ijpdcolor() //set bg color of coutput based on IJPD's value { if (IJPD >= 3.83) { return ("green"); } else { return ("red"); } } ///////////////////////////////////////////////////// function mjpdcolor() //set bg color of coutput based on MJPD's value { if (MJPD >= 4.6) { return ("green"); } else { return ("red"); } } ///////////////////////////////////////////////////// function startVZT3(){ var n=0; n=prompt("What would you like to do? 1: Calculate IJPD 2: Calculate MJPD 3: Exit", "Enter a value from 1-3") switch(n) { case(n="1"): document.getElementById("content").innerHTML='<FORM><h2>Combined IJPD Calculator</h2><p>Install components completed today:</p><INPUT NAME="IJobs" VALUE="3.84" MAXLENGTH="10" SIZE=10><p>Hours taken to the jobs:</p><INPUT NAME="ITime" VALUE="8" MAXLENGTH="10" SIZE=10><h4> Click the button to calculate your IJPD:</h4><INPUT NAME="calc" VALUE="Calculate" TYPE=BUTTON class="cbutton" onClick=iJPDCalc(this.form)><p>Your current combined IJPD for today is:</p> <INPUT NAME="I_JPD" class="output" style=" " id="coutput" READONLY SIZE=10></FORM>'; break case(n="2"): document.getElementById("content").innerHTML='<FORM><h2>Combined MJPD Calculator</h2><p>Trouble components completed today:</p><INPUT NAME="MJobs" VALUE="4.6" MAXLENGTH="10" SIZE=10><p>Hours taken to the jobs:</p><INPUT NAME="MTime" VALUE="8" MAXLENGTH="10" SIZE=10><h4> Click the button to calculate your MJPD:</h4><INPUT NAME="calc" VALUE="Calculate" TYPE=BUTTON class="cbutton" onClick=mJPDCalc(this.form); mjpdcolor();><p>Your current combined MJPD for today is:</p> <INPUT NAME="M_JPD" class="output" style=" " id="coutput" READONLY SIZE=10></FORM>'; break case(n="3"): alert('This page will now close...'); window.close(); break default: document.getElementById("content").innerHTML='<h1 style="padding-top: 40px; color: red;">You need to enter a value! Please try again...</h1>'; break } } /////////////////////////////////////////////////////// </script> </head> <body onload="changeScreenSize(825,775)"> <div id="wrapper"> <div id="sub_wrapper"> <br /> <br /> <input type="button" class="button" onclick="startVZT3()" value="Start VZT3 Web!" /> <br /><br /> <div id="content"> <h3 style="padding-top:60px;">VZT3</h3> </div> </div> <script type="text/javascript"> <!-- trying script to ensure function and dynamic update of this value - doesnt work 2/3/2010 --> document.write(mjpdcolor()); </script> </div> </body> OK, so on the last line of each case statement where it injects html code into the content div, in this code style=" background: ** ** " and in between the ** ** marks, I have added such things as <script type="text/javascript">document.write(mjpdcolor())</script> (or ijpdcolor, depending on which case I am working with). Theoretically, this should pull the value of MJPD (or IJPD), evaluate it for the if statement, then return the value of red or green and set the value of the background dynamically - but of course it doesnt. I have also tried different inline styles and even adding the css id and trying to link it to the mjpdcolor() function, but all to no avail. Can someone help me please?? Thanks everyone, your awesome! Hi there I'm nearly completed on a game, and want to bring in "Lives", basically, rather than the game ending, running "function EndGame ()" I want to allow the player to carry on with "Lives", 3 in fact. Basically, when the player presses a wrong tile, the game needs to carry on, until the last life, life 3 is lost, then "function EndGame ()" runs.. I believe a Global Variable needs to be used? If any help could be given that would be great, also if it could be shown in JSFiddle, that would be great! Many thanks Reply With Quote 12-18-2014, 03:56 PM #2 Dormilich View Profile View Forum Posts Senior Coder Join Date Jan 2010 Location Behind the Wall Posts 3,532 Thanks 13 Thanked 372 Times in 368 Posts Originally Posted by LONDONLAD I believe a Global Variable needs to be used? nope. you can use a global, but you should not. better use the variable/container that you store the player or game status in. Hello everyone, Here's the scenario I wish to plan out. I have an index.htm page ready. I want to be able to put in javascript code into the HTML coding that will write the ip address of the actual server that is hosting the website into a hidden text box. Then I want to insert this ip address into a hyperlink in the original index.htm to link to another html page (this will be a SSL secure page instead i.e. https://<ip address>). Also vice versa. (With SSL index.htm page have code that writes ip into hidden text box then hyperlink to the original http index page) thanks. Hope you follow me var selwindow = window.open('child1.html','_blank','resizable=yes,width='+(screen.width-500)+',height='+(screen.height-500)+''); selwindow.document.selectform.childText.value=document.getElementById('pdetails1').value; I am using this code to assign a value for textbox in the child window. It works well in Internet Explorer, but it shows an error when run in Firefox. It shows: selwindow.document.selectform is undefined. Here, "childText" is the current window textbox id, "pdetails1" is the child window text box id,"select form" is child window form id Hi, I'm not even sure if that's the issue here, but I've isolated it and all the other code is working, so what I'm thinking is that if this: Code: function togglePoly(poly_num) { if (document.getElementById('poly'+poly_num)) { if (document.getElementById('poly'+poly_num).checked) { gpolys[poly_num].show(); } else { gpolys[poly_num].hide(); } } } function createClickablePolyline(poly, html, label) { gpolys.push(poly); var poly_num = gpolys.length - 1; if (!html) {html = "";} else { html += "<br>";} if (html) { GEvent.addListener(poly,'click', function(point) { if (!point) point = poly.getVertex(Math.floor(poly.getVertexCount()/2)); map.openInfoWindowHtml(point,html); }); } label = "<a href='javascript:GEvent.trigger(gpolys["+poly_num+"],\"click\");'>"+label+"</a>"; // add a line to the sidebar html sidebar_html += '<input type="checkbox" id="poly'+poly_num+'" checked="checked" onclick="togglePoly('+poly_num+');">' + label + '<br />'; } document.getElementById("sidebar").innerHTML = sidebar_html; works here to hide/show a line, then this: Code: function show(category) { for (var a=0; a<gpolylines.length; a++) { if (gpolylines[a].mycategory == category) { gpolylines[a].show(); } } for (var i=0; i<pts.length; i++) { if (pts[i].mycategory == category) { pts[i].show(); } } } function hide(category) { for (var a=0; a<gpolylines.length; a++) { if (gpolylines[a].mycategory == category) { gpolylines[a].hide(); } } for (var i=0; i<pts.length; i++) { if (pts[i].mycategory == category) { pts[i].hide(); } } } // this variable will collect the html which will eventually be placed in the sidebar function togglePoly(category) { if (document.getElementById(category)) { if (document.getElementById(category).checked) { show(category); } else { hide(category); } } } function createClickablePolyline(poly, html, name,category) { gpolys.push(poly); var poly_num = gpolys.length - 1; var category = lines[a].getAttribute("category"); midLineArrows(pts, category); GEvent.addListener(poly,'click', function(point) { if (!point) point = poly.getVertex(Math.floor(poly.getVertexCount()/2)); map.openInfoWindowHtml(point,html); }); // add a line to the sidebar html label = "<a href='javascript:GEvent.trigger(gpolys["+poly_num+"],\"click\");'>"+label+"</a>"; sidebar_html += '<input type="checkbox" id="'+category+'" checked="checked" onclick="togglePoly('+category+');">' + label + '<br />'; } document.getElementById("sidebar").innerHTML = sidebar_html; should work here to show/hide lines and arrows the difference of course being that the first code uses poly_num, which is taken directly from the Code: var poly_num = gpolys.length - 1; code (because it only needs to show/hide one line at a time) whereas the second uses the xml attribute "category" from here Code: var category = lines[a].getAttribute("category"); because it's attempting to hide and show a line with arrows on it (the arrows being in the pts array), both of which share the category attribute. It's not throwing up any major errors, but it's not working, either... any suggestions would be great... thanks in advance... I am trying to set my cookies with the click of a button and display them with another button and have them expire one day after visit. I have been having some trouble with this and have written and rewritten code many times. How can I get this code to work? (not very familiar with setting cookies) Any help with this would be greatly appreciated. Thank you. Below is the cookie script I am working on which I am having trouble with: Code: <script> var equipment = document.forms[0].equipment.value; var pDate = document.forms[0].pickupDate.value; var pHour = document.forms[0].pickupHours.value; var pMin = document.forms[0].pickupMinutes.value; var rDate = document.forms[0].returnDate.value; var rHour = document.forms[0].returnHours.value; var rMin = document.forms[0].returnMinutes.value; var first = document.forms[0].firstName.value; var last = document.forms[0].lastName.value; var street = document.forms[0].street.value; var city = document.forms[0].city.value; var zip = document.forms[0].zip.value; var dob = document.forms[0].date.value; var cookieValue = equipment +"~" + pDate + "~" + pHour + "~" + pMin + "~" + rDate + "~" + rHour + "~" + rMin + "~" + first + "~" + last + "~" + street + "~" + city + "~" + zip + "~" + dob var expDate = new Date(); expDate.setTime(expDate.getTime()+(1*24*60*60*1000)); // one day ahead function setCookie(isName,isValue,dExpires) { document.cookie = isName + "=" + isValue + ";expires=" + dExpires.toGMTString() + "path=/"; } function getCookie(isName){ cookieStr = document.cookie; startSlice = cookieStr.indexOf(isName+"="); if (startSlice == -1) {return false} endSlice = cookieStr.indexOf(";",startSlice+1) if (endSlice == -1){endSlice = cookieStr.length} isData = cookieStr.substring(startSlice,endSlice) isValue = isData.substring(isData.indexOf("=")+1,isData.length); return isValue; } function dispCookie(isName) { nValue = getCookie(isName); alert(nValue); } function deleteCookie(isName){ if (getCookie(isName)){ document.cookie = isName + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT"; } } </script> This is the input field in the body part of the form: Code: <input type = "button" value = 'Set Cookies' onclick = "setCookie('anyName','Hello',expDate)"> So I am working on an excercise that the User puts in a Lastname, Firstname, and a score via textboxes. When the user pushes the add student score it should show up in the text area with this format " Brown, John: 92". When looking at the logic, I understand that each text box will need to be different arrays if im right, and then I will have to concat all three arrays into the format and assign it to a variable. Then assign the variable to the value of the text area. I just cannot seem to put the function together or how you would go about it. I just need help with how to go about putting it together. The first code is my body of HTML I'm working with. Code: <body> <div id="content"> <h1>Student Scores</h1> <div id="buddy"> <b>Last Name: </b><input type="text" id="lastName" /> <b>First Name: </b><input type="text" id="firstName" /> <b>Sco </b><input type="text" id="score" /> <input type="button" id="calculate" value="Add Student Scores" /> </div> <fieldset> <legend>Student Scores</legend> <p id="tasks"><textarea id="task_list" rows="20" cols="100"></textarea></p> </fieldset> <div id="yoohoo"> <b>Average sco </b><input type="text" id="averageScore" /> <div> <div id="yes"> <p><input type="button" name="add_task" id="add_task" value="Clear Scores" /></p> <p><input type="button" name="add_task" id="add_task" value="Sort By Last Name" /></p> </div> </body> 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. 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 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! function get_price() { var the_price=1000; if (this.speed=="500MGz") the_price+=200; else the_price+=100; if (this.hdspace=="15GB") the_price+=50; else the_price+=25; if (this.ram=="128MB") the_price+=150; else the_price+=75; return the_price; } function computer(speed,hdspace,ram) { this.speed=speed; this.hdspace=hdspace; this.ram=ram; this.price=get_price; } var work_computer=new computer("2GHz","80GB","1GB"); var home_computer=new computer("1.5GHz","40GB","512MB"); var laptop_computer=new computer("1GHz","20GB","256MB"); var work_computer_price=work_computer.price(); var home_computer_price=home_computer.price(); var laptop_computer=laptop_computer.price(); ___________________________________________________ In the above code, the line I'm having trouble with is marked red. Why is it that when I call the method using ... this.price = get_price; It works fine. But if I assign the object this.price with like this... this.price = get_price(); I get an error? Isn't get_price() a function? So shouldn't the parenthesis be included when the method is called? Why are we suppose to leave out the parenthesis?! I'm confused. Thanks! I currently have a table where the current cell (cursor hover) is highlighted along with the top cell in that column and first cell in row. I want to assign the values in these cells to input text fields. The first column cell is identified by Col1Cell[0] where Cell is the top table data cell of the current column. I can access the value of the cell by Col1Cell[0].innerHTML But when I try to assign this value to a text field nothing happens. I have Code: document.getElementById("tableID").fieldID.value = Col1Cell[0].innerHTML Any ideas? *Edit: I thread title should probably be "Initialize indices..."* I've done quite a bit of research but couldn't find what I need to know so here I am. I have some javascript generated by php that reads a configuration file to add options to a select menu. This is somewhat irrelevant but... these options are removed from the menu when clicked and data related to the option is shown on the page... and the option gets re-added when the data is closed. I need the option to go back in the correct place/order in the select menu... which wouldn't be a problem if I could initialize the indices of the menu's options. They need to be initialized because when the page is created, saved settings are read and certain options are not shown in the list because they may already be shown according to the settings... meaning... since browsers automatically increment the indices of the options by 1 (starting at 0), if data is closed that was initially open and therefore not in the select menu at first... the key/index associated with that data will likely not match the correct menu order. Code: <script type="text/javascript"> function addOptionToSelect(selectID,index,offset,val,txt) { var elSel = document.getElementById(selectID); elSel.options[index+offset].value = val; elSel.options[index+offset].text = txt; } function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { if (oldonload) { oldonload(); } func(); } } } <?php foreach ($props as $k => $prop) { if (!in_array($prop, $_SESSION['crProps'])) { ?> addLoadEvent(addOptionToSelect('propertySelect',<?php echo $k; ?>,1,'?p=<?php echo $prop; ?>&k=<?php echo $k; ?>','<?php echo $prop; ?>')); <?php } } ?> </script> For example, suppose I have the following potential data sets: a,b,c,d,e,f In the config file that helps create the page, suppose it is something like: <Default>0:a|2:c|3:d</Default> (FYI: I've designed it so that the data set names/options are separated by the pipe character ("|") and their corresponding index is the number to the left of the colon.) Then the select menu that is initially generated would be something like: (Every other data set name except for what is already open by default.) <select id="bleh"> <option value="b">b <option value="e">e <option value="f">f </select> And by default, browsers would assign the indices like so: (skipping getElementById and all that...) select.options[0].value = b select.options[1].value = e select.options[2].value = f Whereas, I need it to be initialized like this: select.options[1].value = b select.options[4].value = e select.options[5].value = f So that when the data sets initially open are closed (a, c, or d)... they get put in the correct position in the list. I just thought of something... it's a little inefficient (OCD lol) but it should work and at worst would only cost a couple of milliseconds of processing time. A solution to this problem might be to load the menu with all options so that their indices are correct... and remove the defaults afterward. I'll try it. |