JavaScript - Code Problems Choice
Similar TutorialsI'm developing a simple game that involves a system of interconnected nodes with unidirectional travel between nodes (similar to the circulation system!). The goal of the game is to get from a starting node to an ending node, which can be a variable number of nodes away. The program picks a random starting point, then randomly chooses one of its connecting nodes (cNodes) and pushes it onto a pathArray. A cNode is randomly chosen from this new node and it is pushed onto the pathArray. This continues for a designated number of turns, thus generating a pathArray (invisible to the player). The last element in the pathArray is the endNode and the goal of the puzzle. At each node the player is given two options of travel (though there may be more than two ways to go). One of these options MUST be the correct way if the player has not deviated from the path up until that point. If the player has deviated, this option can be any cNode. The other node is any cNode that does not lead to the endNode. The following code contains a simplified list of nodes that represents the content in my game. The function, however, is taken word for word. In this snippet, the pathArray & startNode have already been generated and I am trying to resolve how to assign "nodeChoice" as either the correct direction of travel (for a player on the correct path) or any random cNode (for a player who has deviated from the path). Keep in mind that the pathArray and cNodes lengths can be any size. Code: <script> //NODES: var nodeA = {name:"A"}; var nodeB = {name:"B"}; var nodeC = {name:"C"}; var nodeD = {name:"D"}; var nodeE = {name:"E"}; var nodeF = {name:"F"}; var nodeG = {name:"G"}; var nodeH = {name:"H"}; var nodeI = {name:"I"}; var nodeJ = {name:"J"}; var nodeK = {name:"K"}; //An array of all nodes in the system: var systemArray = [nodeA, nodeB, nodeC, nodeD, nodeE, nodeF, nodeG, nodeH, nodeI, nodeJ, nodeK]; //Connecting Nodes (cNodes): //(uni-directional, but cyclical) nodeA.cNodes = [nodeB, nodeC]; nodeB.cNodes = [nodeD, nodeE, nodeF]; nodeC.cNodes = [nodeF, nodeG]; nodeD.cNodes = [nodeI, nodeH]; nodeE.cNodes = [nodeJ]; nodeF.cNodes = [nodeK]; nodeG.cNodes = [nodeK]; nodeJ.cNodes = [nodeA]; nodeK.cNodes = [nodeA]; nodeI.cNodes = [nodeA]; nodeH.cNodes = [nodeA]; //The path chosen (generated from code not included here) var pathArray = [nodeA, nodeB, nodeE, nodeJ]; //nodeChoice will represent a cNode from any given node var nodeChoice; //chooseNode is supposed to assign nodeChoice the next element in pathArray if the player on on the right path (if at nodeB, nodeChoice = nodeE). //However, if the user has taken a different path, its cNodes will not be in pathArray in which case a random cNode is assigned to nodeChoice function chooseNode(_node) { //check each cNode to see if any are in pathArray for (var j = 0; j < _node.cNodes.length; j++) { //if a cNode is in pathArray, then we know to assign it nodeChoice... if (_node.cNodes[j] in pathArray) { nodeChoice = _node.cNodes[j]; console.log("choiceNode CORRECT: " + nodeChoice.name); //(for debugging purposes only) } //...otherwise don't do anything in this forLoop/ifStatement }; //if by this point nodeChoice is still undefined, meaning none of the current node's cNodes are in pathArray, assign it any one of its cNodes. if (nodeChoice == undefined) { nodeChoice = _node.cNodes[Math.floor(Math.random()* _node.cNodes.length)]; console.log("choiceNode INCORRECT: " + nodeChoice.name);//(for debugging purposes only) }; }; //Runtime: chooseNode(nodeB); //Result should be only nodeE.name since nodeD is not in the pathArray... console.log(nodeChoice.name); </script> ...however, nodeChoice is assigned either D, E or F randomly and we are given the troubleshooting statement "choiceNode INCORRECT: D (or) E (or) F", indicating that the if-in statement is always ignored. I know that the if-in statement doesn't work but am not sure how else to write it so that each cNode is compared the each element in pathArray, both of which can be of variable lengths... I have two problems with this simple survey that I am trying to write: 1. When I have the "<textarea>" code lines in it put a text-area on the page, but it puts all of the code following that first text-area line into the text-area box and doesn't execute that segment of code. 2. When there is no "<textarea>" (for the sake of seeing if the rest of it worked) it doesn't check the survey. I'm stumped and can't figure out what to do at this point, can someone please help me with this? Code and pictures follow: Code: <html> <head> <title>Survey</title> <script langauge-"javascript"> <!-- var food=new Array("Berries", "Carrots", "Insects", "Salmon", "Salad", "Smelt", "Trout"); var story=new Array("Peter Rabbit", "Molly's Adventure", "Jeremy Fisher", "Mrs. TiggieWinkle", "The Tale of the Two Bad Mice", "Toad's Great Adventure"); function createWindow() { win=open("", "", "menubar, scrollbars"); win.document.write("<head><title>Survey Results</title></head>"); win.document.write("<body bgcolor='white'>"); return win; } function checkSurvey(form) { var outString=""; for(var i=0; i<=2; i++) { if(form.elements[i].value=="") { alert("Please fill in your "+form.elements[i].name); form.elements[i].focus(); return; } outString=outString+form.elements[i].name+":"+form.elements[i].value; outString+="<br>"; } if(!form.Attending[0].checked&&!form.Attending[1].checked) { alert("Please fill in the attendence information"); return; } if(form.Attending[0].checked) { outString+="Attending: Yes<br>"; var index=form.Food.selectedIndex; outString=outString+"Favorite Food: "+food[index]+"<br>"; index=form.Story.selectedIndex; outString=outString+"favorite Story: "+story[index] + "<p>"; } else outString += "Attending: No <p>"; win.document.write(outString); } //--> </script> </head> <body bgcolor="white" onLoad = "win = createWindow()" onUnload = "win.close()"> <b>The Survey</b><p> <i>Please help us by filling our this survey</i><p> <table cellpadding = "3"> <form name = "Survey"> <tr><td>First Name</td> <td colspan = "3"> <input type = "text" name = "First Name" size = "12"></td></tr> <tr><td>Last Name</td> <td colspan = "3"> <input type = "text" name = "Last Name" size = "3"></td></tr> <tr><td>Address</td> <td colspan = "3"> <textarea name = "Address" rows = "5" cols = "30" wrap = "physical"> </teaxtarea></td></tr> <tr><td>Attending?</td> <td><input type = "radio" name = "Attending" value = "Yes">Yes</td> <td><input type = "radio" name = "Attending" value = "No">No</td></tr> <tr><td>Favorite Foods</td> <td colspan="3"><select name = "Food"> <script langauge = "javascript"> <!-- for(var i=0; i<food.length; i++) document.write("<option>" + food[i]); //--> </script></select></td> </tr> <tr><td>Favorite Story</td> <td colspan = "3"><select name = "Story"> <script language="javascript"> <!-- for(var i=0; i<story.length; i++) document.write("<option>" + story[i]); //--> </script></select></td></tr> <tr><td><input type = 'button' value = 'Check Survey' onClick = "checkSurvey(this.form)"></td></tr></form> </table> </body> </html> This may seem like a very noob-like question but I just can't figure it out! I am new to Javascript and I was playing around with if...else.. statements. I made this little code to see if I can make a password activated code. In this case I just want it to open an alert window if the right password is put in. I have tried running this in Chrome, IE and Firefox and none of them worked. Code: <script type="text/javascript"> var n1=prompt("Please enter the correct password."); if (n1=1147) { alert("Congrats! You guessed the right password!"); } else { alert("I am sorry"n1" is not the correct password. Please try again"); } </script> Hello, new to the forums so I don't know really where I should post this. Working with google spreadsheets and google script here if that makes any difference. I want a cell to print the letter O x number of times based on the value of a different cell? For example; If A1 is 3, i want B2 to print O O O. Just as A1 is 5 i want B2 to print O O O O O. I have this bit of code so far and think I could run this as a script, but i keep getting an error "Missing ; after for-loop initializer. (#2) (line 2)" Code: function Dot() { for (i < CellValue) { myOutputString = myOutPutString + "O "; } TargetCell.Formula=myOutputString; } Thank you for any help you can provide....and if there is a better place for this sort of stuff, please let me know. I am having a problem with the follow code with IE9 only. Works fine with any other browser.. Any help? Thanks <a href="javascript:var w = window.open('show_photo.php?ad_id={AD_ID}&img_id={IMG_ID}','','width=450,height=500,toolbar=0,scroll bars=0,statusbar=0,menubar=0,resizable=0');"> </a> We are trying to validate a piece of code on our HTML pages and get the following message - "The text content of element script was not in the required format: Expected space, tab, newline, or slash but found < instead." The code is used to set up the Facebook tags in JavaScript, and does work by itself. However, we're trying to get it to work through validation on http://validator.w3.org Code: <script src="SiteTools.js"> //<![CDATA[ <!-- FacebookSetup('CABLED Project first 6 months', 'images/angela-imiev.jpg'); //--> //]]> </script> Thanks i have code to create a select list. this select list is populated by db query i have two pieces of code i need looked at to fix the problem Code: echo "<select name='LearnedJutsus' id='YourJutsu' onchange='return jutsu()' >"; foreach($learnedJutsuInfo as $v) { echo "<option value='$v'>$v</option>"; } echo "</select></form>"; and most importantly this one! Code: var selection=document.getElementById("x").options[document.getElementById("x").selectedIndex].value; i did not write the above code it was donated to me but it seems to be not working correctly. what i need is an explanation on how it works (which would be best since im foggy with jscript)or a fix for it i basically need it to grab the selected option's information for later use in the program. this is a pivotal part of the system any help appreciated. I've got a form that performs a calculation upon submit. I want it to perform a different calc depending on the choice from a drop down box in the form. Are there any examples of this? or can someone explain how i do it? thanks I was having some problems getting my function to only perform when I click the shoot button. Right now I have it where if you click the buttons and it plays the whole game. I was wondering if there is some way to maybe hide it and then just print the results only when I press the shoot button. I posted my game here its the front page. http://mmoloot4u.com/ I am trying to find out so things so far i thought about doing this, but im not sure the best way. Could i remove assignments from document.getElementByIf('whatever').value from the onclick code for rock, paper, and scissors. Instead define corresponding variables in your <script> area and assign to those variables. Then in 'shoot' you can assign those variables to the corresponding element values? Hello, I am currently making a multiple choice program in JS using 3 arrays, one to call the question, one to store the user answer and one to store the real answer. The answers will then be compared to find the score. I have done most of it, but am still having one problem, I am using prompts and when I call the question, only the text in the if statement "qArray[counter]" is actually showing on the prompt and not the actual question from the array and I wondered if anyone could help? Thanks <html> <head><B>Multiple Choice Quiz</B> </head> <body> <script language = 'JavaScript'> document.write('<br><br>This program allows multiple choice questions to be asked - once finished a calculation will total your score.<br>'); qArray = new Array(); qArray = ['What is the capital of England? London/Paris/Cardiff/Berlin', 'What is the capital of France? London/Paris/Cardiff/Berlin', 'What is the capital of Wales? London/Paris/Cardiff/Berlin', 'What is the capital of Germany? London/Paris/Cardiff/Berlin']; aArray = new Array(); aArray = ['London', 'Paris', 'Cardiff', 'Berlin']; //array of the answers counter = 0; NumberofQuestions = 4; score = 0; while (counter < NumberofQuestions){ if (counter == 0){ question1=prompt('qArray[counter]',''); } if (counter == 1){ question2=prompt('qArray[counter]',''); } if (counter == 2){ question3=prompt('qArray[counter]',''); } if (counter == 3){ question4=prompt('qArray[counter]',''); } counter++; } studentAnswers = new Array(); studentAnswers = [question1, question2, question3, question4]; //an array with the answers the student has inputted counter = 0; while (counter < NumberofQuestions){ if (studentAnswers[counter] == aArray[counter]){ score++; } counter++; } document.write ('You have finished the quiz, your total marks will be calculated.'); //inform student that they have finished document.write('You scored: ',score,' /4'); //prints the score to screen. </script> </body> </html> Hi, I've checked the boards and was unable to find something that matched the code that I have. The code basically uses radio buttons to populate results to a drop-down list depending on the radio button they choose. I'm having trouble figuring out where and how to add the redirection url for each of the value choices in the drop down. I was told something about using window.location('http://url.here') and then to populate the location parameter with the array value. Does this mean I have to redo my script or can another piece of code be added on to make it work. How do I alter my existing code? Thanks in advance for any help I can get: Code: <!DOCTYPE html> <html lang="en"> <head> <script type="text/javascript"> var services = new Array(); services['Tutoring'] = ['Grady', 'Holy Innocents', 'North Springs', 'Paideia', 'Riverwood', 'School Not Listed?']; services['Recording'] = ['John Doe']; function changechoice(choice) { var serviceList = services[choice]; changeSelect('service', serviceList, serviceList); document.getElementById('service').disabled = false; document.getElementById('service').onchange(); } function changeservice(serviceValue) { document.getElementById('output').innerHTML = serviceValue; return; } function changeSelect(fieldID, newValues, newOptions) { selectField = document.getElementById(fieldID); selectField.options.length = 0; if (newValues && newOptions) { for (i=0; i<newValues.length; i++) { selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]); } } } </script> </head> <body> <table width="400" align="center" colspan="2" border="0" rowspan="2"> <tr> <td width="200" align="left"> Pick an option: </td> </tr> <td width="200"> <br> <ul> <input type="radio" name="choice" value="Tutoring" onclick="changechoice(this.value);"> Tutoring<br /> <input type="radio" name="choice" value="Recording" onclick="changechoice(this.value);"> Recording<br /> </ul> </td> <br> <td width="200" align="center" valign="top"> <br> <select name="service" id="service" onchange="changeservice(this.value);" disabled="disabled"> <option> -- Choose an Option -- </option> </select> </td> </table> </body> </html> Hello all, Making a multiple choice quiz using Blue J. My task is to enable the user to add questions and answers. Replace and remove specific answers and questions. Print out all the questions and answers once they are finished. Then quit the program. The user will also need to be able to quit the program at anytime. I am having trouble understanding how i would go about doing this, i figured i would store all the questions using an array or array list? Is an iframe the only way to embed a web page? I would like to embed a web page within a email but some users email clients do not support iframes.
Hi all. I'm learning JS from pretty much scratch and the first thing I'm trying to do is simply make an image fade function. I just can't seem to make it work though, the image starts off at the right opacity (im this case 0.5) but after that the page goes white and the script never stops. It does seem to be counting up normally "opacity: 0.6 opacity: 0.7" etc. though. Code: <img src="1.jpg" id="pic1"> <script type="text/javascript"> var amount = 0.5; var target = document.getElementById('pic1'); function fade() { if (target.style.opacity < 1.0) { target.style.opacity = amount; amount = amount + 0.1; document.write("<br>opacity: " + target.style.opacity); setTimeout("fade()", 1000) //fade(); } } fade(); </script> edit I rewrote it to make it simpler but still having basically the same problem D:! Hi, I have a web form that I'm creating and it has some expandable checkboxes that need to be restricted based on choice. This is my criteria: If someone chooses checkbox number 1, they cannot choose any other checkbox. If someone chooses checkbox number 2, they may also choose number 3 but not 1 or 4, they must also answer the question that appears below. If someone chooses checkbox number 3, they may also choose number 2 but not 1 or 4, they must also answer the question that appears below. If someone chooses checkbox number 4, they cannot choose any other checkbox, and must answer the questions that appears below. One more caveat: If checkbox number 2 is chosen, and they've filled in all three lines of the question below, I need for them to dynamically add more lines as needed. I have attached my web form so you can see what I've done. I've researched these options and tried code from various examples but I can't seem to get it to work. Does anyone know how to accomplish all of this? Thank you in advance! Ok so I have a select box where the value must be passed via the form. If the users selects choice B or Choice C then I want a specific div to show. If they choose choice A then I want the div to hide or remain hidden. It should be hidden on page load. Code: <select name="Event_Type_ID"> <option value="1">Choice A</option> <option value="2">Choice B</option> <option value="3">Choice C</option> </select> <div id="showme"> Content to show if EITHER Choice B or C is chosen. Otherwise this div should be hidden. </div> Can anyone lead me in the right direction? Thanks! I was wondering if someone could help me? In my code below what if answers in question 2 were allowed to be in any order? Like: hips,body,knees or knees,hips,body and so on. How should I modify my code? Anyone please???? Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Quiz</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <script type="text/javascript"> var answer_list = [ ['False'], ['body,hips,knees'] // Note: No comma after final entry ]; var response = []; function getCheckedValue(radioObj) { if(!radioObj) return ""; var radioLength = radioObj.length; if(radioLength == undefined) if(radioObj.checked) return radioObj.value; else return ""; for(var i = 0; i < radioLength; i++) { if(radioObj[i].checked) { return radioObj[i].value; } } return ""; } function setAnswer(question, answer) { response[question] = answer; } function CheckAnswers() { var correct = 0; var resp, answ; for (var i = 0; i < answer_list.length; i++) { resp = response[i].toString(); resp = resp.toLowerCase(); answ = answer_list[i].toString(); answ = answ.toLowerCase(); //################################################################################################# if (resp == answ) { correct++; if(i==0){ document.forms[0].a1c.style.backgroundImage="url('correct.gif')"; document.forms[0].a1c.value = ""; } else{ document.forms[0].a1d.style.backgroundImage="url('correct.gif')"; document.forms[0].a1d.value = ""; } } else{ if(i==0){ document.forms[0].a1c.style.backgroundImage = "url('incorrect.gif')"; document.forms[0].a1c.value = " ANS: False. Position the head snugly against the top bar of the frame and then bring the foot board to the infant's feet."; } else{ document.forms[0].a1d.style.backgroundImage = "url('incorrect.gif')"; document.forms[0].a1d.value = " ANS: " + answ; } //################################################################################################### } } document.writeln("You got " + correct + " of " + answer_list.length + " questions correct!"); } </script> </head> <body> <form action="" method="post"> <div> <b>1. When measuring height/length of a child who cannot securely stand, place the infant such that his or her feet are flat against the foot board.</b><br /> <label><input type="radio" name="question0" value="True" />True</label> <label><input type="radio" name="question0" value="False" />False</label> <br /> <textarea rows="2" cols="85" name="a1c" style="background-repeat:no-repeat"></textarea> <br /> <b>2. When taking a supine length measurement, straighten the infant's <input type="text" name="question1_a" size="10" />, <input type="text" name="question1_b" size="10" />, and <input type="text" name="question1_c" size="10" />.</b> <br /> <textarea rows="2" cols="85" name="a1d" style="background-repeat:no-repeat"></textarea> <br /> <input type="button" name="check" value="Check Answers" onclick="setAnswer(0,getCheckedValue(document.forms[0].question0));setAnswer(1,[document.forms[0].question1_a.value,document.forms[0].question1_b.value,document.forms[0].question1_c.value]);CheckAnswers();" /> </div> </form> </body> </html> I have just used an Analysis Quiz tool (on this page http://javascript.about.com/library/blquizf.htm) to create a quiz which doesn't have right or wrong answers but adds the scores of the answers together. It all works nicely, HOWEVER I require 5 answers as opposed to the maximum of four which has been offered on this site. The (partial) code is: Code: var quiz = new Array(); var r = 0; var analPage = 'result.html'; quiz[r++] =('93726~71~1. How often do you have a drink containing alcohol?~Never~Once a month or less~2 to 4 times a month~2 to 3 times a week~0~3'); quiz[r++] =('48844~37~How many units of alcohol do you have on a typical day when you are drinking?~1-2~3-4~5-6~7-9~0~3'); I thought it would be straight forward and I could add another option at the end of each string and then change the scoring e.g. quiz[r++] =('93726~71~1. How often do you have a drink containing alcohol?~Never~Once a month or less~2 to 4 times a month~2 to 3 times a week~4 or more times a week~0~4'); but this didn't work ... please help! Thank you Hello All, I'm trying to find a script that would be able to do the following: The are two drop down boxes, the first one populating the second (state/county --> town) The first box is single choice, the second is multiple choice. I'm looking for a script that would be able to deal with generating the code for all possible values that could be chosen in the second drop down box. The drop down boxes are part of a form which allow people to search for educational courses within areas of a state/county. I've had a good root around the internet but am rapidly getting confused ... many thanks in advance. Si. |