JavaScript - Question About Syntax In A Finished Script Snippet That Integrates A Loop In A Table
Hello,
In the below script syntax, a simple table converts Celsius degrees into Fahrenheit, using the For loop and integrating it into a table. Code: <html> <head> <title>Celsius-Fahrenheit Converter</title> </head> <body> <table border=3> <tr><td>CELSIUS</td><td>FAHRENHEIT</td></tr> <script language="javascript"> for (celsius=0; celsius<=50; celsius=celsius+1) { document.write("<tr><td>"+celsius+"</td><td>"+((celsius*9/5)+32)+"</td></tr>"); } </script> </table> </body> </html> My questions are about the following script inside the <td> tags: <td>"+celsius+"</td> <td>"+((celsius*9/5)+32)+"</td> 1) why is the script inside the above <td> tags placed between " " ? 2) why is the script inside the above <td> tags placed between + + ? Thanks a lot for your explanation to an absolute Javascript beginner...! Similar TutorialsHi all I'm well aware that I can't post assignments here and expect an answer, however, I have been staring at this code for so long. I feel I am close to the solution (to get the correct output to the browser) but I just cannot get it to count how many moves it takes. I don't want an answer, but a nudge in the right direction would be very grateful. As you can see from the code and the output, it will attempt to write to the browser how many moves, but only '0'. Code: function rollDie() { return Math.floor(Math.random() * 6) + 1; } /* *searches for a number in a number array. * *function takes two arguments * the number to search for * the number array to search *function returns the array index at which the number was found, or -1 if not found. */ function findIndexOf(number, numberArray) { var indexWhereFound = -1; for (var position = 0; position < numberArray.length; position = position + 1) { if (numberArray[position] == number) { indexWhereFound = position; } } return indexWhereFound; } //ARRAYS that represent the board -- you do not need to change these //array of special squares var specialSquaresArray = [1,7,25,32,39,46,65,68,71,77]; //array of corresponding squares the player ascends or descends to var connectedSquaresArray = [20,9,29,13,51,41,79,73,35,58]; //VARIABLES used -- you do not need to change these //the square the player is currently on var playersPosition; //play is initially at START playersPosition = 0; //what they score when they roll the die var playersScore; //the index of the player's position in the special squares array or -1 var indexOfNumber; //MAIN PROGRAM //TODO add code here for parts (iii), (iv)(b), (v), and (vi) // start of question(iii) playersScore = rollDie(); document.write(' Sco ' + playersScore); playersPosition = playersScore + playersPosition; document.write(', Squa ' + playersPosition); indexOfNumber = findIndexOf(playersPosition, specialSquaresArray); if (indexOfNumber != -1) { document.write(', Ladder to Squa ' + connectedSquaresArray[indexOfNumber]); playersPosition = connectedSquaresArray[indexOfNumber]; indexOfNumber = -1; } document.write('<BR>') // end of question(iii) // start of question(iv)(b) while(playersPosition<=80) { playersScore = rollDie() document.write(' Sco ' + playersScore) playersPosition = playersPosition + playersScore document.write(', Squa ' + playersPosition) indexOfNumber = findIndexOf(playersPosition, specialSquaresArray) if(indexOfNumber != -1) { document.write(', Ladder to Squa ' + connectedSquaresArray[indexOfNumber]); playersPosition = connectedSquaresArray[indexOfNumber]; } document.write('<BR>'); } var countMoves = 0; while(countMoves <= 0) { document.write('You took ' + countMoves + ' moves to get out'); countMoves = countMoves + 1 } /*for (var countMoves = 0; countMoves < playersPosition; countMoves = countMoves + 1) { countMoves = countMoves + playersPosition; document.write('You took ' + countMoves + ' moves to get out'); }*/ // end of question(iv)(b) // start of question (v) /*if (playersPosition >=80) { document.write('The player is out'); }*/ // end of question (v) </SCRIPT> </HEAD> <BODY> </BODY> </HTML> Many thanks. Hi could someone help me with this code? What is the correct way to write it. Rules: create an array for the user to type 5 strings in a prompt that will be displayed in an alert box. user must type in the prompt an alert will display what the user typed if the prompt is empty or contains nothing an alert will display telling the user to enter text user clicks ok on the alert box and is sent back to the prompt box Code: function display_moreQuotes(){ var quote2 = new Array(5); var y = 0 for(y=0; y<5; y++) { quote2[y]=prompt('Enter your own quote', ' '); alert(quote2[y]); } if((quote2[y]=' ') || (quote2[y]=null)) { alert("Please enter text"); } } Please explain how/where I went wrong. Thanks! Hey there guys, i have a client who wants to make a school system on his website, now i've done that, however what my client wants is to put wmv files inside every lesson and he wants to be sure that the user who has registered to the online school WATCHES fully all the wmv and then redirect him to a quiz page where he will take a test. My client wants to be sure that the users are watching the wmv files before doing any quiz. SO is there a way where i can know when the wmv file has FINISHED playing so that i would redirect them to another page?? Thank you! Hey guys! I have finally finished my factoring quadratics page! You can see it he http://wdroom.com/factor.html If you see that you received an incorrect solution PLEASE let me know so I can fix it. Credits: Old Pendant, Philip M, bullant in no particular order Thanks so much! When using anonymous wrappers (I guess they are called like that), what does "()" part do at the end of the stack? An example: Code: ( function() {} ) () //Here! What does it do and how can we use it? I have an alert I'm using over in Salesforce to remind sales reps to use a special terms document when quoting. Problem is, the alert is going off for ALL accounts, not just "Account1" and "Account2". Is this line incorrect in syntax or something? if ((isstatus == "Proposal/Price Quote") && (acct == "Account1", "Account2")) Thanks all. This forum has been very helpful for me in the past so this was my first stop! Jeremy Code: <html> <head> <script type="text/javascript" language="javascript" src="/js/functions.js"></script> <script type="text/javascript" src="/soap/ajax/10.0/connection.js"></script> <script type="text/javascript"> function throwalert() { var isstatus = "{!Opportunity.StageName}"; var acct = "{!Opportunity.Account}" var msgg = "Please remember to use a special terms and conditions quote template when quoting this opportunity."; if ((isstatus == "Proposal/Price Quote") && (acct == "Account1", "Account2")) { alert(msgg); } else { window.parent.location.replace = "{URLFOR($Action.Opportunity.View, Opportunity.Id,null,true)};" } } </script> </head> <body onload="throwalert()";> </body> </html> Is it possible to make an app that creates a gif that shows the process of a finished drawing? Im a kid and love drawing and gif . i wanna make app that shows a replay of my initial start of my drawing till the finish product of my drawing in a gif file. thinking to approach this with javascript? would it be possible? Hi, Does anyone know if there is a event or something that fires when Javascript finishes executing. When I load a page, the body's onLoad event fires when it has finished loading but there might be some Javascript that is still running (or javascript that is triggered from the onLoad event itself). And this javascript could add to the page's DOM. So is there any way to detect when the page has REALLY finished loading (ignoring the possibility of setTimeout() etc). I need to know this as I am constructing a webpage-scraper and therefore I need to know when the pages have completely loaded. Thanks, Hey guys, finished my first javascript assignment and was wondering if anyone could confirm it works. I get weird syntax errors on my comp but others have said that it has worked for them, so i'm wondering if anyone else can confirm this. The syntax errors are all claiming that my functions being called in my buttons are not defined, however they clearly are, so i'm thinking it might just be something weird with my machine/browser. Anyway, here's the code and thanks in advance. Code: <html> <head> <script type="text/JavaScript"> var sam = 9; var sally = 8; var donald = 4; var person = prompt("Please enter your name", "Student Name"); if (person != null) { document.getElementById("intro").innerHTML = "Hello " + person + "! Thank you for checking your grades today!"; } function percentage (score) { return score / 10 * 100; }; function goperc() { document.write("Sam's score on the test is " + percentage(sam) + "%, <br \> Sally's score on the test is " + percentage(sally) + "%, <br \> Donald's score on the test is " + percentage(donald) + "%"); }; function highscore() { if (Math.max(90, 80, 40) === 90){ document.write("Sam's score was the highest.")}; else if (Math.max(90, 80, 40) === 80){ document.write("Sally's score was the highest.")}; else{ document.write("Donald's score was the highest.")} }; function lettergrade(grade) { if (grade > 8.9){ document.write("A")}; else if (grade > 7.9){ document.write("B")}; else if (grade > 6.9){ document.write("C")} else{ document.write("F | Warning, your letter grade is very low.")} }; function goletter() { document.write("Sam's letter grade on the test is: " + lettergrade(sam) + ", <br \> Sally's letter grade on the test is: " + lettergrade(sally) + ", <br \> Donald's letter grade on the test is: " + lettergrade(donald)); }; </script> </head> <body> <button onclick="goperc()">Student Percentages</button> <br \> <button onclick="highscore()">Best Grade</button> <br \> <button onclick="goletter()">Student Letter Grade</button> </body> </html> Oh, if anything looks like it's wrong or you see something that could be causing an error, I would love to know. Thanks. Hi folks, I was hoping someone could help explain why the following code actually works. It's from an example in a book I'm working on (Head First Ajax) and I'm not sure why it works and I'd like to understand it. Code: window.onload=initPage; function initPage() { //find thumbnails on the page thumbs=document.getElementById("thumbnailPane").getElementsByTagName("img"); //set the handler for each image for (var i=0; i<thumbs.length; i++) { image=thumbs[i]; //create the onclick function image.onclick=function() { //find the full size image name detailURL = 'images/' +this.title+ '-detail.jpg'; document.getElementById("itemDetail").src=detailURL; //getDetails(this.title); } } } By adding -detail.jpg when an image is clicked, it will replace the current image with a slightly larger version of the image, which has an identical name but with -detail added. My problem is that looking at the for loop, it seems that, since there are four images, the value of i would be 4, and that onclick wouldn't work for images 1,2 and 3. It does work though, so there must be an array being created within the loop (??). I was thinking that the image variable is turned into an array consisting of four images...it's the only explanation that makes sense...but I don't understand how it works. Can someone explain the principle behind this bit of code? I am studying the javascript. I got following codes from json2.js but do not understand syntax of them. if (!this.JSON) { this.JSON = {}; } (function () { ... }()); For 2nd part, why there is () outsider function? and why these is () after function? Thanks a lot. The following code snippet: (this.inputArray is already defined and initialized prior to this code sequence) if(this.inputArray.length >= 0) { this.inputArray[this.inputArray.length] = new Object(); this.inputArray[this.inputArray.length].type = 'pcDisp'; this.inputArray[this.inputArray.length].data = a; } the first line in the code block should create a new array item and initialize it with the various assigments in the next lines. But Firefox complains "this.inputArray[this.inputArray.length] is not defined". This is very disconcerting because the code has to create array items with different data based on conditionals. So I must be able to automatically create new items as necessary. I thought that javascript had 'late binding', but maybe that doesn't apply here. So, does anyone have a clue for me? My site will change color schemes when a user presses the button in the top left. I want to add a third theme though. I can't figure it out though. My html as relevent Code: <!--EXTERNAL FILES--> <link rel="stylesheet" type="text/css" href="main.css" /> <!--[if IE]><link rel="stylesheet" type="text/css" href="mainIE.css" /><![endif]--> <link id="altstyle" rel="stylesheet" type="text/css" href="main.css" /> <script type="text/javascript" src="main.js"></script> <!--STOP EXTERNAL FILES--> <title>Votillity.com</title> <!--CSS INTERNAL--> <!--CSS INTERNAL--> <!--JAVASCRIPT INTERNAL--> <!--JAVASCRIPT INTERNAL--> </head> <body onload="startTime()"> <img class="Zindexsty1" style="position: fixed; top: 0px; left: 0px;" src="http://votillity.com/VotillityLogo1.png" alt="VOTILLITY" /> <img class="Zindexsty2" style="position: fixed; top: 0px; left: 0px;" src="http://votillity.com/VotillityLogo2.png" alt="VOTILLITY" /> <button id="altstyact" class="button" style="position: fixed; top: 0px; left: 170px; width: 60px;">Theme</button> Javascript Code: //ALTERNATE STYLES function changeStyle() { var obj1=document.getElementById('altstyact'); var obj2=document.getElementById('altstyle') test=true; obj1.onclick=function() { test==true? (obj2.href='main2.css',obj1.firstChild.nodeValue='Classic',test=false): (obj2.href='main.css',obj1.firstChild.nodeValue='Ice',test=true) } } if(window.addEventListener) { window.addEventListener('load',changeStyle,false); } else { if(window.attachEvent) { window.attachEvent('onload',changeStyle); } } //STOP ALTERNATE STYLES I don't think you need the css's. If, however, I'm wrong just let me know. Keep in mind that the javascript is external. Here's my site if you need a better look Votillity Thank you Can someone tel me the code to put a dropdown box showing default values as shown below using script ..i,e by enclosing them in document.write in script <CODE> <SELECT NAME="choice" > <OPTION VALUE="1">one </OPTION > <OPTION VALUE="2">two </OPTION > <OPTION SELECTED VALUE=" 5 "> 5 </OPTION> </SELECT> </CODE> How do I re-write this from VBA to JAVASCRIPT? Code: For i = 0 To num_fields - 1 Forgive me, im still new at this stuff. Thanks. Jay So I am wanting to loop through a set of data an undefined amount of times. For this I need a while loop. However, I want the loop to check for the given condition and continue looping on true, but when it breaks on false - to then execute a different command. Code: while(localStorage.getItem(x) != null) { x++; if(localStorage.getItem(x) == null) { localStorage.setItem(x, account.join(";")); break; } } } This works by continuing to loop everytime with the x++ and the nested if statement inside. The problem gets messier as now I need to perform a separate while loop around the entire thing checking for a different condition. To sum things up, what is the most efficient way to perform a while loop and have one action be performed on success and another if it breaks or reaches a defined condition. I have a dice rolling function. The user enters the number of sides, and the dice rolls 36000 times. I track the results, and then display the percentages of each number being rolled as well. I have it to where it displays but only for ONE die ( eg : a 5 sided die, it only displays up to 5, and not 10 ) But the function is rolling for both die, just not displaying. I'm thinking I need to change, in the rollDice function, <=d.side to <=rolled_value, but whenever I do this, I get NaN errors. Any help would be appreciated! Code: <script type="text/javascript"> function Die(side) { this.side = side; this.roll = function () { var result; result = parseInt(((Math.random() * 1000) % this.side) + 1 ); return result; } // <![CDATA[ this.validateNum = function (side) { if (side > 1 && side < 101) return true; else return false; } } function rollDice() { var d = new Die(document.getElementById('number').value); if (d.validateNum(d.side) == true) { var numCount = new Array(d.side); var percent; var rolled_value; for (var i=1; i<=d.side; i++) numCount[i] = 0; for (var j=0; j<36000; j++) { rolled_value = d.roll() + d.roll(); numCount[rolled_value] = numCount[rolled_value] + 1; } for (var k=1; k <= d.side; k++) document.writeln("Number of" + " " + k +"'s" + " " + "rolled" + ' : ' + numCount[k] + '<br/>' ); for (var l = 1; l <= d.side; l++) { percent = new Number(parseFloat(numCount[l] / 36000) * 100).toFixed(2); document.writeln("Percentage of" + " " + l + " " + "being rolled" + ' : ' + percent + '% <br/>'); } } //]]> I have done a basic while loop code but I can not figure out how to make the output print in 4 lines containing 5 numbers each. Can anyone tell me how to specify the number of output that appears on each line? Code: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>example</title> </head> <body> <script type="text/javascript"> <!-- var x = 1; var linebreak="<br/>" while (x <= 20) { document.writeln("" + x + " " + ""); x = x + 1; } // --> </script> </body> </html> Hello, This seems like it should be extremely easy, I think I am missing something fundamental however. First, I have some XML: Code: <aaaaag> <parent text="this is the parent 0"> <child text="zero" /> <child text="one" /> <child text="two" /> <child text="three" /> <child text="four" /> <child text="five" /> </parent> <parent text="this is the parent 1"> <child text="zero" /> <child text="one" /> <child text="two" /> <child text="three" /> <child text="four" /> <child text="five" /> </parent> </aaaaag> And here is a snippet of my js: Code: aaaaag = xmlDoc.getElementsByTagName("aaaaag"); var x = aaaaag[0].childNodes[1].childNodes; cCompA.innerHTML = aaaaag[0].childNodes[1].attributes.getNamedItem("text").nodeValue; // I would have expected childNodes[0] instead !! for (i=1;i<x.length;i+=2) // I would have expected: (i=0;i<x.length;i++) instead !! { cCompB.innerHTML = x[i].attributes.getNamedItem("text").nodeValue + "<br />"; } I really have two questions here, but the first may answer the second. Also it may be worth mentioning I am just trying to work with the "parent 0" for the moment. First, I seem to have hidden nodes in my XML. When accessing the first child as an object, the index is 1, the second is 3 (I have tested this by manually putting in 1,3,5,7,9 etc as the indexs) and so on, rather than starting at 0. I'm not seeing where the hidden nodes are though, and I've run my xml through a validator on W3Cschools.com. I've seen someone recommend not using attributes and instead using a <text>one</text> format, but I am really hoping this isn't the problem as my xml file is fairly long, and it would take quite a bit of effort to rewrite it. The second question is, my for loop only outputs the last child, rather than all the previous children. If anything, I would really expect the last one NOT to get output, because of the i+=2 I am having to do because of the hidden children problem. I'm guessing this is somehow related to the first problem though. Thanks in advance! |