JavaScript - Problems With Switch Statement ...
Hi, im new to this so i was wondering if anyone could tell me where im going wrong? im trying to get my switch statement to work and give me a specific reply for 4 names and if one of these names isnt typed into the promt box then i want an alert box to appear but i cant seem to get it to work. any ideas?
<body> <script type="text/javascript"> //<![CDATA[ var Card_Suit; Card_Suit=window.prompt("Think of a card suit? What suit are you thinking of?","????"); //]]> </script> <h1 style='color: blue'>Your Future In The Cards</h1> <script type="text/javascript"> //<![CDATA[ switch(Card_Suit) { case "clubs": {document.write("<p style='color: black'>"); document.write("Beware of three legged dogs crossing your path</p>"); } break; case "spades": {document.write("<p style='color: black'>"); document.write("Wear brown with pink spots for luck</p>"); } break case "hearts": {document.write("<p style='color: red'>"); document.write("You are going to meet a stranger with two heads</p>"); } break; case "diamonds": {document.write("<p style='color: red'>"); document.write("Your lucky number for today is 13,254,297</p>"); } break; } else window.alert("this is not a card"); } Similar TutorialsHere i am attempting to connect to my javascript two input fields one number and one radio button to change the function computeBudget()... Thank you in advance im desperate for over 48 hours 3 days with trial and error and looking for tutorials for this kind of situation. Code: <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <script> function computeBudget() { var income = document.getElementById('income').value; switch (income) { case "Weekly": this.add((income * 52) / 12); break; case "biWeekly": this.add((income * 26) / 12); break; } var grocery_expenses = document.getElementById('grocery_expenses').value; var car_insurance = document.getElementById('car_insurance').value; var home_mortgage = document.getElementById('home_mortgage').value; var home_utilities = document.getElementById('home_utilities').value; var life_insurance = document.getElementById('life_insurance').value; var monthgain = (income - grocery_expenses - car_insurance - home_mortgage - home_utilities - life_insurance).toFixed(2); monthgain = monthgain.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); document.getElementById('monthgain').innerHTML = "Monthly Net Gain = $" + monthgain; var yeargain = ((income - grocery_expenses - car_insurance - home_mortgage - home_utilities - life_insurance) * 12).toFixed(2); yeargain = yeargain.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); document.getElementById('yeargain').innerHTML = "Yearly Net Gain = $" + yeargain; } </script> </head> <body> <p>Monthly Income: $<input name="income" id="income" type="number" min="1" max="100000000" onchange="computeBudget()"></p> <p>Weekly <input name="income" id="income" type="radio" value="Weekly" onchange="computeBudget()">BiWeekly <input name="income" id="income" type="radio" value="biWeekly" onchange="computeBudget()"></p> <p>Grocery Expenses: $<input id="grocery_expenses" type="number" min="1" max="100000000" onchange="computeBudget()"></p> <p>Car Insurance: $<input id="car_insurance" type="number" min="1" max="100000000" onchange="computeBudget()"></p> <p>Home Mortgage: $<input id="home_mortgage" type="number" min="1" max="100000000" onchange="computeBudget()"></p> <p>Home Utilities: $<input id="home_utilities" type="number" min="1" max="100000000" onchange="computeBudget()"></p> <p>Life Insurance: $<input id="life_insurance" type="number" min="1" max="100000000" onchange="computeBudget()"></p> <h2 id="monthgain"></h2> <h2 id="yeargain"></h2> </body> </html> Reply With Quote 12-27-2014, 11:30 PM #2 Old Pedant View Profile View Forum Posts Supreme Master coder! Join Date Feb 2009 Posts 28,311 Thanks 82 Thanked 4,754 Times in 4,716 Posts Makes no sense. You have this code in the computeBudget() function: Code: this.add((income * 52) / 12); (1) The value of this depends on what invoked the computeBudget function. You invoke it from radio buttons and from text fields. (2) You use a method named add( ) on each of these various fields. There is NO SUCH METHOD defined for either radio buttons or text fields. I have no idea what you intend to do with that value you compute (e.g., ((income * 52) / 12)) but you sure as heck can't add it to anything (unless you write your own method or function named add) and you certainly can't use it to any reasonable effect on this, especially when this refers to a radio button. Hi; Please can somebody help me make this code work for me. i want it to work in such a way that when someone select the ages in the combo box,it will direct the person to another page. Here is it <html> <body> <script type="text/javascript"> page = document.frmOne.cmbAge.value switch (page) { case "1": document.URL = "page1.html" break case "2": document.URL = "page2.html" break case "3": document.URL = "page3.html" break case "4": document.URL = "page4.html" break default: alert("An error occurred, so we are staying here") } </script> </body> <form name="frmOne"> <select name = "cmbAge"> <option value = 1>5 to 16</option> <option value = 2>17 to 30</option> <option value = 3>31 to 45</option> <option value = 4>46+</option> </select> </form> </body> </html> Please help me solve this.. Thanks you. Clement Osei. Im creating a switch statement for this case, but dont know how to start - Create a Switch statement that tests the value of the partyType parameter. If partyType equals "D", store the following text string in a variable named barText: Code: <td class='dem'> </td> If partyType equals "R", barText should equal Code: <td class='rep'> </td> etc.. So since its going to test the value of the partyType parameter, and store the text string in a variable named barText do i begin like: Code: var barText switch (partyType) and how do I write the equals "D", etc. the only examples I have are Code: if (seating = = 'B') doc.write ("Your seat is in the balcony") ^ would i write it like that except seating would = partyType and "Your seat in the balcony" would equal the "<td class etc." ie Code: if (partyType = = "D") doc.write ("<td class='dem'> </td>") Hi everyone, I'm a beginner who has now come across the switch statement and has been trying to understand it with this simple coding i came up with. I think I have the syntex of the switch command correct but I'm trying to get it to work along with a HTML form and a function. I've been trying to figure out what i am do wrng but can not seem to see the solution. can someone guide me to the solution? thanks John Code: <html> <head> <title>Using the switch statement.</title> <script type="text/javascript"> function basegraincheck(){ var basegrain = document.basegrainform.basegrain1.value return basegrain } switch (basegrain) { case 1 : displaygrain = "US Pale ale malt" break case 2 : displaygrain = "Maris Otter Malt" break case 3 : displaygrain = "Crystal Malt" break default: displaygrain = "somethings wrong with the switch statement" } document.write(displaygrain); </script> </head> <body> <form name="basegrainform" action="" method="get" onsubmit="basegraincheck()"> <h2>Select a grain</h2> <br> <p>Pale ale Malt</p> <input type="radio" name="basegrain1" value="1"> <br> <p>Maris Otter Malt</p> <input type="radio" name="basegrain1" value="2"> <br> <p>Crystal Malt</p> <input type="radio" name="basegrain1" value="3"> <br> <input type="submit" value="Submit"> </form> </body> </html> Hello all, This is my first post here, so I apologize if I didn't format this correctly. I am trying to figure out where I went wrong in my code. The objective is to display all lines of the song using a switch statement. I thought I had my head wrapped around it, but apparently not. Would anyone mind pointing me in the right direction, or telling me what I did wrong here? I would be greatly appreciative! Thank you for your consideration folks. Code: <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Excercise 8.11</title> <script type = "text/javascript"> for (var day = 1; day <=5; day++) { switch (day) { case 1: document.write("On the "+day+"st of Christmas, my true love gave to me, A partridge in a pear tree."); case 2: doucment.write("On the "+day+"th day of Christmas, my true love gave to me, Two turtle doves,<br>"); case 3: document.write("On the "+day+"th day of Christmas, my true love gave to me, Three French hens,<br>"); case 4: document.write("On the "+day+"th day of Christmas, my true love gave to me, Four calling birds,<br>"); case 5: document.write("On the "+day+"th day of Christmas, my true love gave to me, Five golden rings,<br>"); break; } } </script> </head> <body> </body> </html> Hi, I'm trying to code a script that will display an approximate postage price based on different combinations of variables, but the numbers I defined for each case aren't reflected in the text box. I'm using a switch statement for all the different combinations of options, which the user will choose by selecting check-boxes. I'd really appreciate if anyone could point out where I'm going wrong. (Additionally, I know that this code probably isn't a very efficient way of doing what I'm doing - I'm open to suggestions on how to improve it.) I've attached all the relevant parts of the code, including how I defined variables originally. Many thanks in advance, Gil Code: <script type="text/javascript"> function count() { var firstclass = document.calc.firstclass.value; var postcard = document.calc.firstclass.value; var numpages = document.calc.numpages.value; var nms = document.calc.nms.value; var large = document.calc.large.value; var numpages = parseInt(document.calc.numpages.value); if (document.calc.grabber.checked) { var vweight = (numpages + 8) * 0.17636981; } else { var vweight = numpages * 0.17636981; } var postageprice = 0; switch(postageprice) { case document.calc.postcard.checked: var postageprice = 28; break; case document.calc.firstclass.checked && vweight <= 1: var postageprice = 44; break; case document.calc.firstclass.checked && vweight <= 2: var postageprice = 61; break; case document.calc.firstclass.checked && vweight <= 3: var postageprice = 78; break; case document.calc.firstclass.checked && vweight <=3.5: var postageprice = 95; break; case document.calc.firstclass.checked && document.calc.large.checked && vweight <= 1: var postageprice = 88; break; case document.calc.firstclass.checked && document.calc.large.checked && vweight <= 2: var postageprice = 105; break; case document.calc.firstclass.checked && document.calc.large.checked && vweight <= 3: var postageprice = 122; break; case document.calc.firstclass.checked && document.calc.large.checked && vweight <= 4: var postageprice = 139; break; case document.calc.firstclass.checked && document.calc.nms.checked && vweight <= 1: var postageprice = 64; break; case document.calc.firstclass.checked && document.calc.nms.checked && vweight <= 2: var postageprice = 81; break; case document.calc.firstclass.checked && document.calc.nms.checked && vweight <= 3: var postageprice = 98; break; case document.calc.firstclass.checked && document.calc.nms.checked && vweight <= 3.5: var postageprice = 105; break; case document.calc.firstclass.checked && document.calc.nms.checked && document.calc.large.checked && vweight <= 1: var postageprice = 122; break; case document.calc.firstclass.checked && document.calc.nms.checked && document.calc.large.checked && vweight <= 2: var postageprice = 139; break; case document.calc.firstclass.checked && document.calc.nms.checked && document.calc.large.checked && vweight <= 3: var postageprice = 156; break; case document.calc.firstclass.checked && document.calc.nms.checked && document.calc.large.checked && vweight <= 4: var postageprice = 173; break; default: var postageprice = 0 } document.calc.pay.value = postageprice } </script> <form name="calc" method="POST"> <input type="text" name="numpages" size="10" value=10 onpropertychange="count()" onkeypress="keypress(event)" onclick="SelectAll()"> <input type=button name=clearnumber value="Clear" onclick="document.calc.numpages.value=0"> <p></p> <input type="checkbox" name="firstclass" size="10" onclick="count()"><p> <input type="checkbox" name="large" size="10" onclick="count()"></p> <p> <input type="checkbox" name="nms" size="10" onclick="count()"></p> <p> <input type="checkbox" name="postcard" size="10" onclick="count()"></p> <p> <input type="checkbox" name="grabber" size="10" onclick="count()"></p> <p>$<input type="text" name="pay" size="10"> $<input type="text" name="perthousand" size="10"> </p> </form> Thanks again. Hi my goal was to archive a switch statement in javascript to check the users IE versions. Allowing me to switch my javascript code to which will only work in other versions. Yet I don't know if a switch would be appropriate in this matter. Any tips ore suggestions are more then welcome. Please let me know if a if statement would be better. it involves large javascript code. Code: <script type="text/javascript" language="javascript"> if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { var ieversion = new Number(RegExp.$1); switch (ieversion) { case 8: document.write("IE 8") break; case 5: document.write("IE 5") break; case 6: document.write("IE 6") break; case 7: document.write("IE 7") break; } } </script> Hey everyone, I'm a newbie writing a tic tac toe program using OOP. It was simple setting it up so that a player could click on a box to put an X or an O there, but I've run into serious issues when trying to make it so a player couldn't overwrite the AI's choice and the AI couldn't overwrite the player's. An example of this would be if I made the top right box an X and the AI then made the center box an O, and then I accidentally clicked the center box and made it into an X. I want to prevent that. Every box on the grid is an object with the property of "taken" that helps the program know if a box is empty or not, so as to avert any overwriting in the first place. If the box is empty, this.taken = 0. If the box is filled by a player, taken = 1. If filled by AI, taken = 2. I made it matter whether it was AI or human so later i can check if one of them got tic tac toe. Anyway, by default the constructor class sets this.taken = 0. But the method for checking availability and writing the X or O uses a switch which checks if taken = 0. If it is, it sets taken to either 1 or 2 and writes the necessary symbol. If taken = 1 or 2, it just alerts the player that the spot is taken. But for some reason the switch statement can't tell when taken = anything other than 0. It always executes the code for 0 even though the code for 0 inherently makes it so that taken never equals 0 again, which means case 0 cannot happen anymore. Below is the code with notes. Code: function main(input){//start of main function// function Click(who, where, what){ //this is the method for checking if it's taken or not and writing the X or O if it isn't// /*the argument who represents a number. 0 is no one, 1 is human, 2 is AI; where is a string literal representing the spot on the grid*/ switch(this.taken){ case 0: this.taken = who; document.getElementById(where).innerHTML = what; break; case 1: alert("this spot is taken"); break; case 2: alert("this spot is taken"); }//end switch }//end Click function Box(inputhere){//start of class// this.taken = 0; this.pick = Click; } //end of Box class// //object declarations (I cut out most of them and left only the relevant ones// var topleft = new Box(); var topmid = new Box(); var topright = new Box(); var centerright = new Box(); //end of object declarations// switch (input){ /*in each .pick(), the first arg is whether or not a player chose it (1 = player did, 2 = comp did). The second arg is which box and the third is whether to put an X or O. The input variable in the switch statement is an argument passed through main() when the player clicks on a box. Topleft passes 1.1, topmid passes 1.2 and so on.*/ case 1.1:{ //The first instance of .pick() in each case is what the player did. The second is what the AI will do in repsonse.// topleft.pick(1, "topleft", "X"); topmid.pick(2, "topmid", "<span>O</span>"); break; }//end of case 1.1 case 1.3:{ topright.pick(1, "topright", "X"); centerright.pick(2, "centerright", "<span>O</span>"); break; }//end of case 1.3 }//end of switch }//end of main// Is there anyone who has any idea why on earth this is happening? I've been at it for an embarrassing amount of hours. Also, thanks to anyone who even considers helping : ) (feel free to flame me if my code sucks or my post is too long or anything). My goal is to have one big picture center with 4 smaller pictures to the left that you click on and is target to the center. When you click on the center it will zoom. I haven't worked on it in a few years and not able to find the person who wrote the code. I added the zoom coding to the picture switch. The zoom works fine but when you click the smaller images the image is not viewable. Coding in the head Code: <!--Image Viewer--> <script language="javascript" type="text/javascript"> <!-- function canManipulateImages() { if (document.images) return true; else return false; } // loadPosterImage function loadPosterImage(imageURL) { if (gImageCapableBrowser) { document.imagePoster.src = imageURL; return false; } else { return true; } } gImageCapableBrowser = canManipulateImages(); // --> </script> <!--End Image Viewer--> <!--Picture Zoom--> <script> // C.2004 by CodeLifter.com var nW,nH,oH,oW; function zoomToggle(iWideSmall,iHighSmall,iWideLarge,iHighLarge,whichImage){ oW=whichImage.style.width;oH=whichImage.style.height; if((oW==iWideLarge)||(oH==iHighLarge)){ nW=iWideSmall;nH=iHighSmall;}else{ nW=iWideLarge;nH=iHighLarge;} whichImage.style.width=nW;whichImage.style.height=nH; } </script> <!--End Picture Zoom--> The body code Code: <!--Picture #4--> <tr> <td><A href="F:\mamies\santa_pic\purple_bottom.gif" onClick="return(loadPosterImage('F:\mamies\santa_pic\purple_bottom.gif'))"> <img src="F:\mamies\santa_pic\purple_bottom.gif" border=1 align=center width=56 height=75></A> </td> </tr> </table> <table align="center" border="1" cellspacing="0" cellpadding="5" height="10" bgcolor="#002152" bordercolor="#980008"> <tr> <!--Image Zoom--> <td><img name="imagePoster" src="F:\mamies\santa_pic\purple_front.gif" border="0" width="354" height="502" onclick="zoomToggle('354px','502px','708px','1004px',this);"> <!--End Image Zoom--> Thanks for your help Charlene Hello all I have a video playlist useing iframe http://alohainvesting.com/html5/Html5player.html Is there a way to get same results without iframes? i just want to switch items on nav to the wrapper window. can this be done? Thanks just a general question really... now that I've finally started using switches, it seems to me that they're just a big if /else if statement, with an else thrown in at the end for the default. but that can't be right. I know that in javascript there are a million ways to achieve the same result, but why would they (whoever they are) go to the trouble of making two basic operations that do exactly the same thing? to me it seems that switches are better for lots of conditions and if else is a quick way to work with two or three, but apart from readability, are there any inherent advantages in choosing one approach over the other? all opinions appreciated, and I hope I don't start another argument. Hello everyone, I am using javascript and I have a radio button that the user selects and I have a function to see which button was selected, but i'm trying to use the return of that if statement in another statement. Basically another part of the function is dependent on what the user selects in the radio button. Here is what I have so far (I have some things in there that might not work because i'm trying to figure out what works): Code: <script type="text/javascript"> function getSelectedRadio() { len = document.dates.dep.length // returns the array number of the selected radio button or -1 if no button is selected if (document.dates.dep[0]) { // if the button group is an array (one button is not an array) for (var i=0; i<len; i++) { if (document.dates.dep[i].checked) { return i } } } else { if (document.dates.dep.checked) { return 0; } // if the one button is checked, return zero } // if we get to this point, no radio button is selected return -1; } function Calculate() { var i = getSelectedRadio(); if (i == -1) { alert("Please select if Marine entered Delayed Entry Program"); } else { if (document.dates.dep[i]) { return document.dates.dep[i].value; } else { return document.dates.dep.value; } } if (document.dates.yearDEAF.value < 1985 && document.dates.monthDEAF.value < 01 && document.dates.dayDEAF.value < 01 && first return from above ) { document.dates.yearDEP.value = (document.dates.yearDEAF.value); document.dates.monthDEP.value = (document.dates.monthDEAF.value); document.dates.dayDEP.value = (document.dates.dayDEAF.value); document.dates.yearPEBD.value = (document.dates.yearDEAF.value); document.dates.monthPEBD.value = (document.dates.monthDEAF.value); document.dates.dayPEBD.value = (document.dates.dayDEAF.value); } else if (document.dates.yearDEAF.value < 1985 && document.dates.monthDEAF.value < 01 && document.dates.dayDEAF.value < 01 && second return from above ) { document.dates.yearPEBD.value = (document.dates.yearAFADBD.value); document.dates.monthPEBD.value = (document.dates.monthAFADBD.value); document.dates.dayPEBD.value = (document.dates.dayAFADBD.value); document.dates.yearDEP.value = "N/A"; document.dates.monthDEP.value = "N/A"; document.dates.dayDEP.value = "N/A"; } } </script> I color coded in red the returns i'm trying to reference and where they need to be. Is this possible, and if so how can I do it? I haven't been able to find anything on the internet so far. Any help is greatly appreciated! Here is the code, in full: <htmll"> <head><title></title> <script type="text/javascript"> <!-- HIDE FROM INCOMPATIBLE BROWSERS function checkGrade(grade, value) { switch (grade) { case "A": if(grade == '90') window.alert("Your grade is excellent."); break; case "B": window.alert("Your grade is good."); break; case "C": window.alert("Your grade is fair."); break; case "D": window.alert("You are barely passing."); break; case "F": window.alert("You failed."); break; } } // STOP HIDING FROM INCOMPATIBLE BROWSERS --> </script> </head> <body> <form name="gradeForm"action="Your Grades"> <input type="text" name="grade" /> <input type="button" value="Check Grade" onclick="checkGrade(document.gradeForm.grade.value);" /> </form> </body> </html> What's throwing me off is the "A" in the case. As well, "(document.gradeForm.grade.value)" I need to make it a IF statement, but not sure how to call that function. I want to make a function that will also play a sound byte when you click on the large image. i need the sound byte to change with the images. Here is the code that i am using. Code: intImage = 2; function swapImage() { switch (intImage) { case 1: IMG1.src = "images/picture1-lg-over.png" IMG2.src = "images/picture2-sm-top.png" IMG3.src = "images/picture3-sm-btm.png" intImage = 2; return(false); case 2: IMG1.src = "images/picture2-lg-over.png" IMG2.src = "images/picture1-sm-top.png" IMG3.src = "images/picture3-sm-btm.png" intImage = 3; return(false); case 3: IMG1.src = "images/picture3-lg-over.png" IMG2.src = "images/picture2-sm-top.png" IMG3.src = "images/picture1-sm-btm.png" intImage = 1; return(false); } } i have tried many things that involved each case to contain a different IMG1.onClick=""; value but it doesnt seem to change when the case changes. I have also tried making another switch/case that would change the value of the onClick event.. nothing. any sugestions? Hi There, I need your help, I can't seem to get this work, which it theorecticly should work any ideas? <script> var x = 3 switch(x){ case x > 0: alert("overdue") break case x = 0: alert("due today") break case x < 0: alert("will be due") break } </script> Much thanks for everyones help. Cheers, Jay how to make a switch that goes on a button(sorry that i cant describe it better)
Give me an example for switch statements. I had to create one that tests value of parameter using a text string, I came up with this value Code: function createBar(partyType,percent){ switch(partyType) { case D: <td class='dem'></td> break; Should I use " or ' between the dem? I am using break statements. do all breaks should end with string or do i need the bracket? I hope this does not seem like i getting people to do homework for me again,, just want to verify if i did this area correctly? I have a function I call like this: var theBase = getBase(percent); then, the function: function getBase(percent) { var base=''; switch (percent) { case percent.indexOf("this") == 4: base = "that" break; case percent.indexOf("thisOther") == 9: base = "thatOther" break; } return base; } However, even if percent.indexOf("this")==4 (or if any other case matches perfectly), it never enters that case and assigns a value to 'base'. What am I doing wrong? Hi guys. I was wondering if its possible to switch a form action using javascript. Because im trying to have a search field on my main site for my forum and website. By having two boxes underneath my search field so people can select if the want to search my phpbb forum ore my site. Well anyway, mabey switching the form action is not the right approach. Any tips are welcome thanks. Hi, Any help would be greatly appreciated. Below is the javascript that I am having a problem with. The two id's in question are at the end of the javascript. fyi Its for a form. What will happen is that the user selects the first dropdown with an id of 00N20000001HjsR. They then selects another dropdown with an id of 00N20000001Hp9Q. What I want is that on the second dropdown, if the user selects the value of Beauty Therapy, it will change the value of the first dropdown (id 00N20000001HjsR) to 'ANCB'. The problem I have at the moment is that it is not overriding the original dropdown selection. Any ideas on how to solve this? Much appreciated in advance, thanks!!! Code: <script type="text/javascript"> //check if prospectus is on document.formRec.onsubmit = function() { return ValidForm(); }; function ValidForm(){ if (document.getElementById("first_name").value == ""){ alert("Please enter your first name"); document.getElementById("first_name").focus(); return false; } if (document.getElementById("last_name").value == ""){ alert("Please enter you last name"); document.getElementById("last_name").focus(); return false; } if (document.getElementById("email").value == ""){ alert("Please enter your email address"); document.getElementById("email").focus(); return false; } if (document.getElementById("phone").value == ""){ alert("Please enter your contact number"); document.getElementById("phone").focus(); return false; } if (document.getElementById('00N20000001Hp9a').value== "--None--"){ alert("Please choose you country of citizenship"); document.getElementById('00N20000001Hp9a').focus(); return false; } if (document.getElementById('00N20000001HjsR').value== "--None--"){ alert("Please select type of study you are interested in"); document.getElementById('00N20000001HjsR').focus(); return false; } switch (document.getElementById('00N20000001Hp9Q').value) { case "--None--": alert("Please select area of study you are interested in"); document.getElementById('00N20000001Hp9Q').focus(); return false; break; case "Beauty Therapy": document.getElementById('00N20000001Hp9Q').value = "Beauty Therapy"; document.getElementById('00N20000001HjsR').value = "ANCB"; break; } return true; } </script> |