JavaScript - Conditional Statement W/i A Loop Correct Syntax
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! Similar TutorialsI just found this forum! I'm glad because I wanted to ask some javascript questions before. There was a question at work before at why one would use the following: if (a=='1') ... or if ('1'==a) ... Is there any kind of advantage of using one of the other? Thanks for any response! This is the loop I'm trying to use to check for bullets hitting rocks. the function worked if I used actual numbers instead of the j variable, but I wanted to loop through all the rocks. Can anyone see why the inner function loses the j index and says asteroids[j] is undefined? the hit test is removing the bullets! it's working! the asteroids[j] was used in the hit test! I'm getting testy. LOL Code: for(z in player.bullets){ for(j in asteroids){ if( pnpoly( asteroids[j].points_x, asteroids[j].points_y, player.bullets[z].x - asteroids[j].x, player.bullets[z].y-asteroids[j].y)==true) { player.bullets.shift(); asteroids[j].hits++; for(i in asteroids[j].points_x){ asteroids[j].points_x[i]*=.5; asteroids[j].points_y[i]*=.5; } }; } Here's the whole script. This is the asteroids script somebody needed help with a few days ago. I just couldn't resist making this. I love asteroids so much it's hard to describe. That game was simply the most awesome thing ever at the time. (I'm a product of the eighties) Code: <html> <head> <title></title> <script type="text/javascript" src="excanvas.js"></script> </head> <body> <script> function pnpoly(xp, yp, x, y){var c=0;for(i in xp){ j=i++;if((((yp[i]<=y)&&(y<yp[j]))||((yp[j]<=y)&&(y<yp[i])))&&(x<(xp[j]-xp[i])*(y-yp[i])/(yp[j]-yp[i])+xp[i])){c =!c}} return c} var canvas = null; var c2d = null; //... window.onload = init; function init() { thrustFlame=false asteroids = [{ x: 470, y: 290, angle: 1.71, inertia: .5, inertiaAngle: 1.2, points_x: [-30, -27, 5, 15, 30, 15,-5], points_y: [ -5, 15, 30, 27, -5, -25, -30], hits:0 }, { x: 270, y: 290, angle: 1.71, inertia: .75, inertiaAngle: 1.9, points_x: [-30, -10, 0, 20, 40, 20, -10], points_y: [0, -20, -50, -30, 0, 20, 20], hits:0 }] player = { x: 50, y: 50, angle: 1.71, inertia: 0, inertiaAngle: 0, bullets:[] } canvas = document.getElementById('canvas'); ctx = canvas.getContext('2d'); setInterval(step, 60); } function step() { for (i in asteroids) { asteroids[i].angle += i % 2 == 0 ? .05 : -.05 asteroids[i].x < 0 ? asteroids[i].x = canvas.width : asteroids[i].x %= canvas.width asteroids[i].y < 0 ? asteroids[i].y = canvas.height : asteroids[i].y %= canvas.height asteroids[i].x += Math.sin(asteroids[i].inertiaAngle) * asteroids[i].inertia; asteroids[i].y += -Math.cos(asteroids[i].inertiaAngle) * asteroids[i].inertia } ctx.fillStyle = "rgb(0,0,0)" ctx.fillRect(0, 0, canvas.width, canvas.height); for (u = 0; u < asteroids.length; u++) { ctx.save(); ctx.beginPath() Asteroid_draw(asteroids[u]); ctx.closePath(); ctx.strokeStyle = "#eeeeff"; ctx.stroke(); ctx.restore(); } ctx.save(); ctx.beginPath() Player_draw(player); ctx.closePath() ctx.strokeStyle = "#eeeeff"; ctx.stroke(); ctx.restore() if(thrustFlame){ ctx.save(); ctx.beginPath() Player_drawFlame(player); ctx.closePath() ctx.strokeStyle = "#ff0000"; ctx.stroke(); ctx.restore() thrustFlame=false } player.x < 0 ? player.x = canvas.width : player.x %= canvas.width player.y < 0 ? player.y = canvas.height : player.y %= canvas.height if (player.inertia > .025) player.inertia -= .025 player.x += Math.sin(player.inertiaAngle) * player.inertia; player.y += -Math.cos(player.inertiaAngle) * player.inertia for(i in player.bullets){ player.bullets[i].timer++; if(player.bullets[i].timer > player.bullets[i].range)player.bullets.shift() player.bullets[i].x < 0 ? player.bullets[i].x = canvas.width : player.bullets[i].x %= canvas.width player.bullets[i].y < 0 ? player.bullets[i].y = canvas.height : player.bullets[i].y %= canvas.height player.bullets[i].x += Math.sin(player.bullets[i].inertiaAngle) * player.bullets[i].inertia; player.bullets[i].y += -Math.cos(player.bullets[i].inertiaAngle) * player.bullets[i].inertia ctx.save(); ctx.beginPath() ctx.fillStyle="rgba(255,255,0,1)" ctx.arc(player.bullets[i].x,player.bullets[i].y,1.5,0,3.14,true) ctx.fill() ctx.closePath() ctx.restore(); } for(z in player.bullets){ for(j in asteroids){ if( pnpoly( asteroids[j].points_x, asteroids[j].points_y, player.bullets[z].x - asteroids[j].x, player.bullets[z].y-asteroids[j].y)==true) { player.bullets.shift(); asteroids[j].hits++; for(i in asteroids[j].points_x){ asteroids[j].points_x[i]*=.5; asteroids[j].points_y[i]*=.5; } }; } } } function Asteroid_draw(obj) { ctx.translate(obj.x, obj.y) ctx.rotate(obj.angle); ctx.moveTo(obj.points_x[0], obj.points_y[0]); for (i = 0; i < obj.points_x.length - 1; i++) { ctx.lineTo(obj.points_x[i], obj.points_y[i]); } ctx.lineTo(obj.points_x[0], obj.points_y[0]) } function Player_draw(obj) { ctx.translate(obj.x, obj.y); ctx.rotate(obj.angle); //Points {0,-12}{7,5}{-7,5} ctx.moveTo(0, -12); ctx.lineTo(7, 4); ctx.lineTo(-7, 4); ctx.moveTo(-7, 4) ctx.lineTo(0, -12); } function Player_drawFlame(obj) { ctx.translate(obj.x, obj.y); ctx.rotate(obj.angle); ctx.moveTo(-2, 2); ctx.lineTo(0, 12); ctx.lineTo(2, 2); } document.onkeydown = function (event) { keyDown(event) }; function keyDown(event) {event=!event?window.event:event if (event.keyCode == 32) { player.bullets.push({x:player.x,y:player.y,inertia:player.inertia+10,inertiaAngle:player.angle,timer:0,range:40}) } if (event.keyCode == 37) { player.angle -= .1 } /*left*/ else if (event.keyCode == 39) { player.angle += .1 } /*right*/ else if (event.keyCode == 38) { thrustFlame=true var x1= Math.cos(player.inertiaAngle)* player.inertia; var y1= Math.sin(player.inertiaAngle)* player.inertia; var x2= Math.cos(player.angle)* .2; var y2= Math.sin(player.angle)* .2; var xR= x1 + x2; var yR= y1 + y2; var lengthR= Math.sqrt(xR*xR+yR*yR); if (lengthR==0){angleR=0} var angleR= Math.acos(xR/lengthR); if (yR<0)angleR= 0-angleR; player.inertia=lengthR // player.inertiaAngle = (player.inertiaAngle*19 + player.angle) / 20 player.inertiaAngle =angleR } /* up*/ else if (event.keyCode == 40) { player = { x: 50, y: 50, angle: 1.71, inertia: 0, inertiaAngle: 0 } } /*down*/ } </script> <canvas id="canvas" width="600" height="600"></canvas> </body> </html> Hello, On a simple form, there is a radio button group with two radio buttons, a text box, and a submit button. The first radio button is checked(selected) by default. The text box input has the onChange event handler so that if the text is changed, the second radio button will be checked(selected). The problem is the input radio name contains a hyphen that breaks the JavaScript and the name can not be changed. What is the correct syntax for referencing a hyphenated form input radio name in the onChange event? Here is the form that works correctly with no hyphen in the input radio name: Code: <form name="myFormGood" action="" onsubmit="return false;"> Good Form with no hyphen in radio button name<br> <input name="radio1" type="radio" value="4" checked> First Option<br> <input name="radio1" type="radio" value="5"> Second Option<br><br> Change the text to select the Second Option<br> <input type="text" name="text1" onChange="document.myFormGood.radio1[1].checked = 'true';" size="10" value=" "><br><br> <input type="button" name="submit" value="It Works!"> </form> Here is the form that breaks the JavaScript because it has a hyphen in the input radio name: Code: <form name="myFormBad" action="" onsubmit="return false;"> Bad Form with hyphen in radio button name breaks JavaScript<br> <input name="radio-1" type="radio" value="4" checked> First Option<br> <input name="radio-1" type="radio" value="5"> Second Option<br><br> Change the text to select the Second Option. Nothing Happens.<br> <input type="text" name="text1" onChange="document.myFormBad.radio-1[1].checked = 'true';" size="10" value=" "><br><br> <input type="button" name="submit" value="It Doesn't Work!"> </form> I'm learning to program, and am having some issues with the syntax of my "if" statement. I've looked online but still can't get it to work. Here's the code: Code: function checks(){ if(document.myform.checkbox.checked == true){ window.open("http://www.espn.html", "mywindow"); } else{ document.write("hello world"); } } //document.write("hello world");} I know the function is being called properly because when I hit "submit" on the form the document.write("hello world"); statement prints on a new page. But for some reason when I call the function and that part is commented out, nothing happens. Any idea what I'm doing wrong? I tried looking online but can't figure anything out. Thanks in advance. Hi there, I am attempting to set up a very basic menu to drive a program for two different games. I need the menu to process using a primed sentinel controlled loop (where the quit option is the sentinel). I have already set up a function for each game and was hoping to call the function when the user selects a game. I also want to both (a) keep a count of the number of games played and (b) keep a points score, which is to be displayed before the menu is shown agin. When the user quits, I want the final number of points and games played written to document body. I have only very basic knowledge of JavaScript so I realise this is probably a simple answer but I've spent a heap of time on it so far and the menu still has glitches. Any help would be greatly appreciated! This is what I have so far: SENTINEL = 0; MESSAGE_MENU = 'Menu: 1. Pattern Game, 2. Guessing Game, 0. Quit' userInput = parseInt(prompt(MESSAGE_MENU)); while(userInput != SENTINEL) { userInput = parseInt(prompt(MESSAGE_MENU)); if(userInput == 1) { patternGame(); gamesPlayed++; alert('Number of Games Played: '+gamesPlayed) alert('Total Points Scored: '+totalPoints) } else if(userInput == 2) { guessingGame(); gamesPlayed++; alert('Number of Games Played: '+gamesPlayed) alert('Total Points Scored: '+totalPoints) } else { alert('Not a valid input. '+MESSAGE_MENU); } } document.writeln('Total Points: '+totalPoints); document.writeln('Games Played: '+gamesPlayed); 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...! I wonder if anyone could help me get started with this: I have a website written in a legacy font. I want to give the option to view the same site in Unicode. This would mean transforming about 50 font-glyphs in the html file before it appears in the browser. Now the difficulty is I want this processing only to happen on demand, so the html will still be in the legacy font, and those who need it will be able to use Unicode. I want to do this with an optionally included js file. Can someone give me some idea of how this can be accomplished I will then try and fill in the details. I have two divs, one is the triggering and the other is the hidden one. Hovering the first div will show the hidden div. To hide the div the user must "mouseout" from this div, however if the user "mouseout" from the first div nothing will happend and that is the problem because if there are another group next to them, and the user pass from one triggering div to the next this will show the two hidden divs stacking over one another. This is for a horizontal menu (something like www.oracle.com). The actual code is this: Code: <div id="option_a"><p>FIRST OPTION</p> <div id="option_a_menu"> **HERE ARE LIST, DIVS, IMGS** </div> </div> <div id="option_b"><p>SECOND OPTION</p> <div id="option_b_menu"> **HERE ARE LIST, DIVS, IMGS** </div> </div> The JS: Code: function init() { oOptionA=document.getElementById("option_a"); oOptionAmenu=document.getElementById("option_a_menu"); oOptionB=document.getElementById("option_b"); oOptionBmenu=document.getElementById("option_b_menu"); //behaviors addEvent(oOptionA,'mouseover',goOptionA); addEvent(oOptionAmenu,'mouseout',outOptionAmenu); addEvent(oOptionB,'mouseover',goOptionB); addEvent(oOptionBmenu,'mouseout',outOptionBmenu); } function goOptionA() { oOptionAmenu.style.visibility="visible"; } function outOptionAmenu() { oOptionAmenu.style.visibility="hidden"; } function goOptionB() { oOptionBmenu.style.visibility="visible"; } function outOptionBmenu() { oOptionBmenu.style.visibility="hidden"; } The user will hide the option A menu only when his mouse clears the div that showed up. However is he hover the triggering div and go just to the next triggering div (The second div) will trigger the visibility of their menu, but the previously menu will still on stage, stacking the two menus. I was trying this to solve the problem: Code: ...addEvent(oOptionA,'mouseout',goOptionA); function goOptionA() { if (oOptionAmenu!=hover) { oOptionAmenu.style.visibility="hidden"; } else { oOptionAmenu.style.visibility="visible"; } } However, this is not working, something is wrong with the "oOptionAmenu!=hover" but how can I do this ? Thanks in advanced I'm a beginner and I've gotten myself into a mess, trying to build a page with several dropdowns that change an image conditionally. The idea is: if I pick option b in dropdown a, Picture-A appears. If I go to dropdown 2, and pic option 3, picture-A changes to A3 Or if I pic option 5, picture-A changes to a5. And I want to go in reverse too: if I make a new change to the first dropdown, it would remember what the 2nd option was. But I'm not sure if I've got any syntax worth a dang on this. I've got a mess of a page, he www.mergecreate.com/test25q.html Here's the inline text on the rollover option. It doesn't seem to work: <li><a href="javascriptassit4('6')" onMouseover="change1('pic8','image2')" onclick="if('pic2' == 'image2'){image2.src="images/leaf_shapes/crenate/leaf_elliptic_crenate.gif"};" onMouseout="change1('pic8','image_off');">Test Auriculate overlay</a></li> Hi, I'm trying to create a test using Javascript. Actually, I did this in PHP, but we need to put it a server that does nor run it, I think I can convert it to Javascript. I hope it'll be work as in PHP somehow. Test will be composed of 15 questions and each question has either "Yes" or "No" as answer. And, I use radio buttons here for answers. By the way, there will be more than one radio groups. Now, I want to check the value of clicked radio button in each group and use an if-statement to determine if it's correct. And, if it's correct, I want to increment a variable by 1. Finally, by the resulted variable incremented for each question in the test, I want to use another if-statement to show specific result message for and interval of that variable. I tried this for one radio button like this: Code: <script language="JavaScript"> function get(form) { var ans1 = document.form.q1; var score = 0; for( i = 0; i < ans1.length; i++ ) { if( ans1[i].checked && ans1[i].value == no ) { score++; alert(score); } else {alert(score);} break; } } </script> <form name="form" method="get"> <input type="radio" name="q1" value="yes">Yes <input type="radio" name="q1" value="no">No* <input type="button" name="button" value="button" onclick="get(this.form)" /> </form> By the code above, it should alert 1 if "No" is checked and button is clicked and alert 0 if "Yes". This was a preliminary job for me to understand. And I couldn't do even this. Thank you. Hi everyone, So I know enough to make an image change when you click on something, but not enough to do what I want to do. Code: <img name="ImageState" src="Image1.jpg" alt="Image"> <A HREF="javascript:void(0)" onclick="ImageState.src='Image1.jpg'">Link 1</A> <A HREF="javascript:void(0)" onclick="ImageState.src='Image2.jpg'">Link 2</A> <A HREF="javascript:void(0)" onclick="ImageState.src='Image3.jpg'">Link 3</A> <A HREF="javascript:void(0)" onclick="ImageState.src='Image4.jpg'">Link 4</A> <A HREF="javascript:void(0)" onclick="ImageState.src='Image5.jpg'">Link 5</A> The problem is that I want the images to only advance in the proper order. For example, if "Image2.jpg" is currently displayed, I want to make it so that only clicking on "Link 3" will advance it to "Image3.jpg" while the other links are still there but do nothing if you click on them. Can anyone tell me how to do this please? Hi, I modified the below code to make a conditional statement. The condition is .. if a user selects Childs_Fullname then the BV_Choice-1 and BV_Choice_2 should be required fields. I am still able to save the form without the above conditional required fields. What am I doing wrong?? Can some point me in the right direction. Thanks Vinny ------------------------------------------------------------------ <script language="JavaScript" type="text/javascript"> function BV_Class_show() { var val = document.getElementById("x_Child1_Fullname").value; if (document.getElementById("x_Child1_Fullname").value != "") { // a name was selected if (document.getElementById("x_Child1_BV_Choice_1") value == "")||(document.getElementById("x_Child1_BV_Choice_2") value == "" )) { // either not selected alert ("You must make a selection from x_Child1_BV_Choice_1 and x_Child1_BV_Choice_2"); return false; } } </script> Hello! I'd like to ask if it is possible to use conditional operators var = condition ? var1 : var 2 to do the same job as the if-else statements I wrote in red below: Thank you! Code: <p id="text">change text colour</p> <br /> <a onclick="allsorting();">sort in both ascending & descending orders</a> <div></div> <script> /* if & else */ function changetext(){ document.getElementById('text').onclick = function (){ swapcolour(this); } } function swapcolour(text){ if(text.style.color == 'black'){ text.style.color = 'red'; } else {text.style.color = 'black'} } window.onload = changetext; </script> I can't seem to figure out how to do this. I want the user to hit the submit button on the form and then have a few conditional statements ran to if they left any blank textfields and to see if a certain textfield contains numbers. Then I want the user to be directed to a new page if the statements are true. Here is the function code: Code: <script type="text/javascript"> function notEmpty(elem, elem1, elem2, helperMsg, helperMsg2){ if(elem.value.length == 0){ alert(helperMsg); elem.focus(); return false;} if(elem1.value.length == 0){ alert(helperMsg); elem.focus(); return false;} if(elem2.value.length == 0){ alert(helperMsg); elem.focus(); return false;} var alphaExp = /^[a-zA-Z]+$/; if(elem1.value.match(alphaExp)){ return true; }else{ alert(helperMsg2); elem.focus(); return false;} return true; } </script> And here is the form code: Code: <center> <div id="main"> <form align="center" method="post" action="/wamp/www/recipesubmit2.php"> <font color="red"><i>* = Required Field</i></font> <table border="0" bordercolor="darkblue"> <tr><td align="right"><font color="red">*</font>Recipe Name:</td><td><input type='text' id='recipeName' size=50></td></tr> <tr><td></br></td></tr> <tr><td align="right"><font color="red">*</font>Ingredients:</td><td><input type='text' id='ingredients' size=50></td></tr> <tr><td></td><td><font font size="2" color="red">Reminder: </font><font font size="2">Make sure you put a space between each ingredient.</br>Example: <b>chicken cream of mushroom soup</b>. DO NOT PUT</br>MEASUREMENTS! It is also important to correctly spell the</br>ingredients otherwise your recipe may not be found when searched.</td></tr> <tr><td></br></td></tr> <tr><td align="right"><font color="red">*</font>Directions:</td><td><textarea id='description' cols=50 rows=10></textarea></td></tr> <tr><td></br></td></tr> <tr><td align="right"><font color="red">*</font>Cook/Prep Time:</td> <td><select name="cooktimedrop"> <option value="zerofive">0-5</option> <option value="sixten">6-10</option> <option value="elevenfifteen">11-15</option> <option value="sixteentwenty">16-20</option> <option value="twentyonetwentyfive">21-25</option> <option value="twentysixthirty">26-30</option> <option value="thirtyonethirtyfive">31-35</option> <option value="thirtysixforty">36-40</option> <option value="fortyonefortyfive">41-45</option> <option value="fortysixfifty">46-50</option> <option value="fiftyonefiftyfive">51-55</option> <option value="fiftysixsixty">56-60</option> <option value="sixtyoneplus">61+</option> </select> minutes</td> <tr><td></br></td></tr> <tr><td align="right"><font color="red">*</font>Gen </td> <td><select name="genredrop"> <option value="alcoholic">Alcoholic</option> <option value="appetizers">Appetizers</option> <option value="beverages">Beverages</option> <option value="breads">Breads</option> <option value="breakfast">Breakfast</option> <option value="cakes">Cakes</option> <option value="candies">Candies</option> <option value="casseroles">Casseroles</option> <option value="cookies">Cookies</option> <option value="crockpot">Crockpot</option> <option value="desserts">Desserts</option> <option value="dipsdressings">Dips/Dressings</option> <option value="entrees">Entrees</option> <option value="fatfree">Fat Free</option> <option value="georgeforeman">George Foreman</option> <option value="halal">Halal</option> <option value="herbal">Herbal</option> <option value="italian">Italian</option> <option value="jams">Jams</option> <option value="jello">Jell-O</option> <option value="lowfat">Low Fat</option> <option value="mexican">Mexican</option> <option value="puddings">Puddings</option> <option value="rice">Rice</option> <option value="salads">Salads</option> <option value="sauces">Sauces</option> <option value="seafood">Seafood</option> <option value="snacks">Snacks</option> <option value="soups">Soups</option> <option value="vegan">Vegan</option> <option value="vegetarian">Vegetarian</option> <tr><td></br></td></tr> <tr><td align="right">Submitted By:</td><td><input type='text' id='submittedBy' size=40></br></td></tr> <tr><td></br></td></tr> <tr><td></td><td align="right"><input type='submit' onsubmit="notEmpty(document.getElementById('recipeName'), document.getElementById('ingredients'), document.getElementById('description'),'You have not filled in all required fields.', 'I thought I said no measurements! (No Numbers)')" value='Submit Recipe'></td></tr> </form> </div> </center> Hello, First, thank you to anyone that can help. Basically I am trying to create a Cascade Dropdown with a submit button, that once clicked, takes them to a URL depending on the choices they made in the cascade dropdown. I have the cascade dropdown working properly but do not know how to create a submit button that says, "If Cookeville = Cosmetology; then go to this URL." Any ideas or suggestions? I will need to create this type of conditional statement for each choice. My code so far is below. Thank you again in advanced. Code: <form id="locations"> <label for="categories">categories: </label> <select name="categories" id="categories"> <option value="1">Cookeville, TN</option> <option value="2">Lebanon, TN</option> <option value="2">Dalton Beauty School</option> <option value="2">Daphnie</option> </select> <label for="items">items: </label> <select name="items" id="items" type="submit"> <option class="2" value="0">Cosmetology</option> <option class="2" value="1">Cosmetology Instructor</option> <option class="2" value="2">Instructor Trainee</option> <option class="1" value="3">Cosmetology</option> <option class="1" value="4">Cosmetology Instructor</option> <option class="1" value="5">Esthetician</option> <option class="1" value="6">Instructor Trainee</option> <option class="1" value="7">Nail Technology</option> </select></form> <script type="text/javascript"> //Applies cascading behavior for the specified dropdowns function applyCascadingDropdown(sourceId, targetId) { var source = document.getElementById(sourceId); var target = document.getElementById(targetId); if (source && target) { source.onchange = function() { displayOptionItemsByClass(target, source.value); } displayOptionItemsByClass(target, source.value); } } //Displays a subset of a dropdown's options function displayOptionItemsByClass(selectElement, className) { if (!selectElement.backup) { selectElement.backup = selectElement.cloneNode(true); } var options = selectElement.getElementsByTagName("option"); for(var i=0, length=options.length; i<length; i++) { selectElement.removeChild(options[0]); } var options = selectElement.backup.getElementsByTagName("option"); for(var i=0, length=options.length; i<length; i++) { if (options[i].className==className) selectElement.appendChild(options[i].cloneNode(true)); } } //Binds dropdowns function applyCascadingDropdowns() { applyCascadingDropdown("categories", "items"); //We could even bind items to another dropdown //applyCascadingDropdown("items", "foo"); } //execute when the page is ready window.onload=applyCascadingDropdowns; </script> Fellow Coders, I am trying to follow this tutorial (http://econym.org.uk/gmap/basic16.htm) What I would like to do is have in my XML file, a parameter for a total (some random number) and I want to plot a marker based on this number. So like, if the total="5" then marker would be red, if it was 10, marker would be green. I see in the tutorial that they are storing the possible markers in an array, I get that. What I don't know how to do is plot the markert depending on the value of the total field in the XML file. This is what I'm trying to do. CONDITIONS: If a person selects a Friday Class but not a Saturday Class the Total Cost Field will automatically enter $99. If a person selects a Saturday Class but not a Friday Class the Total Cost Field will automatically enter $99 as well. If a person selects both a Friday & Saturday Class the Total Cost field will automatically be $159. I found the following code and so far only have it changing when a Friday class is entered. I have no idea where to go from here. Please help. Code: <!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" xml:lang="en" lang="en"> <head> <title>Test</title> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> </head> <body> <div> <p><span class="style1">Friday Class:</span> <select id="fridayClass" > <option> </option> <option value="Class1"> Class 1 </option> <option value="Class2"> Class 2</option> <option value="Class3"> Class 3 </option> </select> </p> <p> <span class="style1">Saturday Class:</span> <select id="saturdayClass" > <option> </option> <option value="Class1"> Class 1 </option> <option value="Class2"> Class 2</option> <option value="Class3"> Class 3 </option> </select> </p> </div> <div><span class="style1">Total Cost:</span> <input type="text" id="totalCost"/></div> <script> window.onload = function () { var friday = document.getElementById('fridayClass'), saturday = document.getElementById('saturdayClass'); friday.onchange = function () { totalCost.value = '$99.00'; }; }; </script> Ok, I'm nearly pulling my hair out with this one. I have been looking at this code for two evenings now, and rewrote it 4 times already. It started out as jQuery code and now it's just concatenating strings together. What I'm trying to do: Build a menu/outline using unordered lists from a multidimensional array. What is happening: Inside the buildMenuHTML function, if I call buildMenuHTML, the for loop only happens once (i.e. only for 'i' having a value of '0'.) If I comment out the call to itself, it goes through the for loop all 3 times, but obviously the submenus are not created. Here is the test object: Code: test = [ { "name" : "Menu 1", "url" : "menu1.html", "submenu" : [ { "name" : "menu 1 subitem 1", "url" : "menu1subitem1.html" }, { "name" : "menu 1 subitem 2", "url" : "menu1subitem2.html" } ] }, { "name" : "Menu 2", "url" : "menu2.html", "submenu" : [ { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" }, { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" } ] }, { "name" : "Menu 3", "url" : "menu3.html", "submenu" : [ { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" }, { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" } ] } ]; Here is the recursive function: Code: function buildMenuHTML(menuData,level) { var ul; if (level == 1) { ul = "<ul id='menu'>"; } else { ul = "<ul class='level" + level + "'>"; } for (i = 0; i < menuData.length; i++) { menuItemData = menuData[i]; ul += "<li>"; ul += "<a href='" + menuItemData.url + "'>" + menuItemData.name + "</a>"; if (typeof menuItemData.submenu != 'undefined') { ul += buildMenuHTML(menuItemData.submenu,level + 1); } ul += "</li>"; } ul += "</ul>"; return ul; } Here is how the function is called initially: Code: buildMenuHTML(test,1); This is it's return value (with indentation added for readability): Code: <ul id='menu'> <li><a href='menu1.html'>Menu 1</a> <ul class='level2'> <li><a href='menu1subitem1.html'>menu 1 subitem 1</a></li> <li><a href='menu1subitem2.html'>menu 1 subitem 2</a></li> </ul> </li> </ul> 'Menu 2' and 'Menu 3' don't show up! I'm sure it's something small that I'm overlooking, but any help would be appreciated. Hi all, I had posted earlier on the NaN issue. I have worked some more on my test file. Basically I want the user to select an option depending on whether he/she has Paracetamol in syrup or drops form. Once this is selected, automatically a different div for syrup or for drops should be seen depending on what the user selected earlier. After this on pushing the calculate button, the output should be appropriate depending on the strength of the solution either for drops or syrup. I have put together what I think code that should work but it stubbornly refuses to do otherwise. I have attached the relevant file. If it doesn't work, obviously there is something wrong but what it is eludes me. Any help will be appreciated greatly, Thanks, Hi 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. |