JavaScript - Switch Problem
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? Similar TutorialsI'm currently attempting to make a unit conversion tool. I'd like for the user to select which unit to start and which unit to convert too. EX: 1 foot comes out to 12 inches. So far it's not going well. I have two list boxes, named "firstmeasure" and "secondmeasure". For the purpose of this post we will use only 3 different unit in the list boxes, centimeters, feet, and inches. I also have two text boxes used to show the output and for the user to put in a number to convert. And of course, a button that calls the function (I'd prefer it to do the function automatically, but I'll get to that later). I'm trying to use variable arrays and using the value of the list box options to define which value the array will use. Then in the function I'm trying to use a switch/case statement to allow it to figure out which numbers to plug into an equation. My problem is that it seems to automatically go to the last case option regardless of what the list box is. This is the form that in the HTML file: Code: <form action="" name="lengthform" id="lengthform" > <p> <label >Select first measurement</label> <br/> <select id="firstmeasure" name="firstmeasure" > <option value="1">Centimeter</option> <option value="2">Feet</option> <option value="3">Inch</option> </select> <input type="text" id="input" name="input" value="1" /> <br/> <br/> <label >Select Second measurement</label> <br/> <select id="secondmeasure" name="secondmeasure" > <option value="1">Centimeter</option> <option value="2">Feet</option> <option value="3">Inch</option> </select> <input type="text" id="output" name="output" /> </p> <input type="button" onclick="calculate()" value="Convert!" /> </form> This is whats in the Java file: Code: var centimeters1 = new Array() ; centimeters1["1"] = "1" ; //centimeters centimeters1["2"] = "0.032808399" ; //feet centimeters1["3"] = "0.393700787" ; //inches var feet1 = new Array() ; feet1["1"] = "30.48" ; //centimeters feet1["2"] = "2" ; //feet feet1["3"] = "12" ; //inches var inches1 = new Array() ; inches1["1"] = "2.54" ; //centimeters inches1["2"] = "0.0833333333" ; //feet inches1["3"] = "3" ; //inches function calculate() { var measure1 = document.lengthform.elements["firstmeasure"] ; var measure2 = document.lengthform.elements["secondmeasure"] ; var A = document.lengthform.input.value ; var B ; var C ; switch (measure1.value){ case "1" : B = centimeters1[measure2.value] ; C = A * B document.lengthform.output.value = C case "2" : B = feet1[measure2.value] ; C = A * B document.lengthform.output.value = C case "3" : B = inches1[measure2.value] ; C = A * B document.lengthform.output.value = C }//end switch }//end function So, measure1 reads the value of the first list box, and measure 2 reads the value of the second list box. I tried using a switch case statement instead of writing a ton of if statements. Which I also tried and it gave me the same problem. If there is a much better way to do a conversion tool, than I would love to learn how. Any help on fixing this seemingly easy problem would be great. Edit: Do I have to use an "int" variable in the switch statement? I'm using Adobe Dreamweaver and it won't allow to me to create a variable using "int", it just gives me a syntax error. 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 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 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? how to make a switch that goes on a button(sorry that i cant describe it better)
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. 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 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? Hi all, so "click" I have got my head around oop. And can see the huge advantages of using it - encapsulation, interfaces, reusability of code and the ultimate creation of my own library (after I have read my new christmas book "Apress Pro JavaScript Design Patterns") I am moving my brain over to writing work in oop and am going to write a little portfolio with an attachment of the starts of a personal unobtrusive JavaScript library. My question/advice needed is - is there a situation where it is better to use procedural programming in Javascript for say a "simple" site, does oop work slow the script down? (think this maybe a silly question - and I can check in firebug) Or does it really not matter? What for you guys/gals are the advantages of oop in JavaScript? Thanks in advance for any insights into this -- I have posted a similar question for Php-- 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, Please help code not working.i want the alert message to pop up when a cmbprop is selected. <script type="text/javascript"> function PropertyOwn(property) { prop=document.frmone.cmbprop.value switch(property) { case"0": // no error occured break case"1": alert("I am a rich men") break case"2": alert("i am a poor men") break case"3": alert("Thank God for this opportunity") break default: alert("Just try again") } } </script> <form name="frmone"> <select name="cmbprop" onchange="propertyOwn(this.value)"> <option value=0>--choose from one--</option> <option value=1>I have BMW</option> <option value=2>I rent a sigle room</option> <option value=3>Seing possibilities</option> </select> </form> Thanks. Clement Osei Here 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, 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> " <body> <a href="biography.html" id="biography">BIO</a> <script type="text/javascript"> window.onload = initRedirect; function initRedirect() { switch(getElementById.onclick) { case "getElementById"biography".onclick": alert("Four score and seven years ago..."); return false; default: } } </script> </body> " I don't quite understand the getElementById property. Is there a way I can get it so that I click on the biography link and an alert displays? hi, I have a few links on my website as follows: Code: <a href="javascript:switchid('a6');">Link 6</a> but when I view source it comes out like this: Code: <a href='javascript:switchid('>Link 6</a> Can someone please help? I know theres a lot of codes out there online for this but I cannot seem to get any of them to work for me. I am trying to make my layout for an item page for an online store. I'd like one big image, with one or 2 thumbnails under it which when clicked will switch the big image. Clicked, not mouseover. Lets say my big images would be REG1.jpg and REG2.jpg, the first being the image on the page that will switch. THUMB1.jpg and THUMB2.jpg being the thumbnails. Is there a simple way to do this or is the code a complete mess like I've been seeing on so many pages? I'd say I have an intermediate understanding of HTML and I've just started teaching myself javascript but I'm starting to fall off the wagon, I can't decipher the stuff coming up in these example codes. Any help would be thoroughly appreciated!! I am using a script I found and trying to make some changes. It is a avatar creating script that will put a face together. The tabs are different parts of the face. The problem is I don't want all the different hair colors and styles to show and in the color tab when you click a color it will bring up the hair styles in that color only in the next tab. I have tried if(isset($_GET['color'])) { but this is only showing the first color style cant it to work. So then tried to use switch like this PHP Code: <p> <span name="color"> <img src="herotmb/color0.png" alt="" /><input name="avatar[color]" type="radio" value="black" id="black" onclick="swapImage(this);" /> <img src="herotmb/color1.png" alt="" /><input name="avatar[color]" type="radio" value="brown" id="brown" onclick="swapImage(this);" /> <img src="herotmb/color2.png" alt="" /><input name="avatar[color]" type="radio" value="darkbrown" id="darkbrown" onclick="swapImage(this);" /> <img src="herotmb/color3.png" alt="" /><input name="avatar[color]" type="radio" value="yellow" id="red" onclick="swapImage(this);" /> <img src="herotmb/color4.png" alt="" /><input name="avatar[color]" type="radio" value="red" id="yellow" onclick="swapImage(this);" /> </span> </p> <?php switch(id){ case 'BLACK': echo ' <p> <img src="heroimg/hair0-black.png" alt="" /><input name="avatar[hair]" type="radio" value="hair0-black" /> <img src="herotmb/hair1-black.png" alt="" /><input name="avatar[hair]" type="radio" value="hair1-black" /> <img src="herotmb/hair2-black.png" alt="" /><input name="avatar[hair]" type="radio" value="hair2-black" /> <img src="herotmb/hair3-black.png" alt="" /><input name="avatar[hair]" type="radio" value="hair3-black" /> <img src="herotmb/hair4-black.png" alt="" /><input name="avatar[hair]" type="radio" value="hair4-black" /> <img src="herotmb/hairNone-black.png" alt="" /><input name="avatar[hair]" type="radio" value="hairNone" /> </p>'; break; case 'BROWN': echo ' <p> <img src="herotmb/hair0-brown.png" alt="" /><input name="avatar[hair]" type="radio" value="hair0-brown" /> <img src="herotmb/hair1-brown.png" alt="" /><input name="avatar[hair]" type="radio" value="hair1-brown" /> <img src="herotmb/hair2-brown.png" alt="" /><input name="avatar[hair]" type="radio" value="hair2-brown" /> <img src="herotmb/hair3-brown.png" alt="" /><input name="avatar[hair]" type="radio" value="hair3-brown" /> <img src="herotmb/hair4-brown.png" alt="" /><input name="avatar[hair]" type="radio" value="hair4-brown" /> <img src="herotmb/hairNone-brown.png" alt="" /><input name="avatar[hair]" type="radio" value="hairNone" /> </p>'; break; case 'DARKBROWN': echo ' <p> <img src="herotmb/hair0-darkbrown.png" alt="" /><input name="avatar[hair]" type="radio" value="hair0-darkbrown" /> <img src="herotmb/hair1-darkbrown.png" alt="" /><input name="avatar[hair]" type="radio" value="hair1-darkbrown" /> <img src="herotmb/hair2-darkbrown.png" alt="" /><input name="avatar[hair]" type="radio" value="hair2-darkbrown" /> <img src="herotmb/hair3-darkbrown.png" alt="" /><input name="avatar[hair]" type="radio" value="hair3-darkbrown" /> <img src="herotmb/hair4-darkbrown.png" alt="" /><input name="avatar[hair]" type="radio" value="hair4-darkbrown" /> <img src="herotmb/hairNone-darkbrown.png" alt="" /><input name="avatar[hair]" type="radio" value="hairNone" /> </p>'; break; case 'RED': echo ' <p> <img src="herotmb/hair0-red.png" alt="" /><input name="avatar[hair]" type="radio" value="hair0-red" /> <img src="herotmb/hair1-red.png" alt="" /><input name="avatar[hair]" type="radio" value="hair1-red" /> <img src="herotmb/hair2-red.png" alt="" /><input name="avatar[hair]" type="radio" value="hair2-red" /> <img src="herotmb/hair3-red.png" alt="" /><input name="avatar[hair]" type="radio" value="hair3-red" /> <img src="herotmb/hair4-red.png" alt="" /><input name="avatar[hair]" type="radio" value="hair4-red" /> <img src="herotmb/hairNone-red.png" alt="" /><input name="avatar[hair]" type="radio" value="hairNone" /> </p>'; break; case 'YELLOW': echo ' <p> <img src="herotmb/hair0-yellow.png" alt="" /><input name="avatar[hair]" type="radio" value="hair0-yellow" /> <img src="herotmb/hair1-yellow.png" alt="" /><input name="avatar[hair]" type="radio" value="hair1-yellow" /> <img src="herotmb/hair2-yellow.png" alt="" /><input name="avatar[hair]" type="radio" value="hair2-yellow" /> <img src="herotmb/hair3-yellow.png" alt="" /><input name="avatar[hair]" type="radio" value="hair3-yellow" /> <img src="herotmb/hair4-yellow.png" alt="" /><input name="avatar[hair]" type="radio" value="hair4-yellow" /> <img src="herotmb/hairNone-yellow.png" alt="" /><input name="avatar[hair]" type="radio" value="hairNone" /> </p>'; } ?> nothing shows up. I have searched and found this and tried it but get more errors because I'm not just using images Code: http://www.codingforums.com/showthread.php?t=205694 How can I get this to work ? 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. 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> I have a DIV that contains a sentence, call it Text_A. When a button is clicked, I would like to have Text_A replaced by Text_B. Text_A = The sky is blue. Text_B = The grass is green. How would I do this with simple javascript? A non-programmer thank you immensely. Mike |