JavaScript - Quick Switch Case Question
Here is what i'm trying to do and I'm not sure if it will work with a switch, but i'd be better than writing a million if else statements.
Code: var = c var = z switch (c) { case c > 1 && < 10: z = 5; break; case c > 10 && < 20: z = 15; break; default: z = 0; } I think you see what I'm trying to do. I have a variable 'c' and it is input by the user and I want to make variable 'z' set according to what 'c' is. I know the above code doesn't work, but I'm not sure why. I've tried a million different things to try and get it to work, but it always just goes to default when it displays 'z'. Any help would be great. Thanks. Similar TutorialsHi 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 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? I am returning the present time - then using the .substr to remove all digits except the last two on the right (i.e effectively returning the value 32 from 65344532) I am then looping, subtracting 11 from that number until the value is less than 11. The intent being to then return the value from the appropriate matching array ID I have an array sl1 sl1[0]; sl1[1]; sl1[2]; sl1[3]; sl1[4]; sl1[5]; sl1[6]; sl1[7]; sl1[8]; sl1[9]; sl1[10]; The problem arises with evaluating two digit numbers beginning with zero - In cases where the last two numbers are greater than 09, the looping returns a 1 digit number for valuse less than 10, in cases where the last two digits begin with zero the loop will not begin. I have attempted to use the switch(n) to determine if any 01, 02, 03 ... etc exists but this is not evaluating correctly - is this due to using the date/time object and if so is there a good way to convert this to either a numeric or string datatype where the case can be evaluated correctly? Thanks in advance! -------- So, I have a list of items that need to have a new preset list item appear based on what day it is. I have the date script working (to test, change the first case to some random date and change the third case to todays date - 10192010 - It will fire that document.write). What I need the cases to do though, is set the visibility of certain list items. This is just an example, there will be around 20 list items in the final project. As you can see in the first two cases, I've tried a couple different routes to no avail. Any help would be fantastic. The Code (class references are irrelevant to this example, they belong to the final project): Code: <html> <head> <script type="text/javascript" language="JavaScript"> /* Count up from any date script- By JavaScript Kit (www.javascriptkit.com) Over 200+ free scripts here! */ function getToday(yr,m,d){ var today=new Date() var todayy=today.getYear() if (todayy < 1000) todayy+=1900 var todaym=today.getMonth() var todayd=today.getDate() var simpledate=todaym+""+todayd+""+todayy var firstItem=document.getElementById("listOne"); var secondItem=document.getElementById("listTwo"); var thirdItem=document.getElementById("listThree"); switch(simpledate){ case "10192010": firstItem.style.visibility="visible"; secondItem.style.visibility="hidden"; thirdItem.style.visibility="hidden"; break; case "10202010": document.getElementById("listOne").style.visibility="visible"; document.getElementById("listTwo").style.visibility="visible"; document.getElementById("listThree").style.visibility="hidden"; break; case '10212010': document.write("This code works...why can't I change an elements style within this case block also?") break; default: document.write("Something is wrong") } } //enter the count up date using the format year/month/day getToday(2010,07,26) </script> </head> <body> <div id="theList"> <ul class="rounded"> <li id="listOne" style="display:block;" class="arrow"><a href="#kliwComic-MvPDualBoot"><font size="1px">11/17/10 - </font>MvP: Dual Boot</a></li> <li id="listTwo" style="display:block;" class="arrow"><a href="#kliwComic-MvPTouchScreen"><font size="1px">11/18/10 - </font>MvP: Touch Screen</a></li> <li id="listThree" style="display:block;" class="arrow"><a href="#kliwComic-MvPVista"><font size="1px">11/19/10 - </font>MvP: Vista</a></li> </ul> </div> </body> </html> I'm a bit of a hack at this. Any input is greatly appreciated. Thanks again. Hello I have issue and question. My software is taking value "inputVal" and assign it to the variable inputValue for example: assdsf than value "inputTyp" and assign it to the variable inputType for example: string so I want now to switch betwean "inputType" using "switch case" Every case has some "code" inside. So if my software choosed for example: inputType which is for example STRING value I want to RUN case 'string': But it doesn;t works ;/ It doesn't goes to any case;/ what is wrong with the code ;/ every case should test according regular expressions is string a string or email is email or number is number etc... and result: "false or true" should be assign to new variables for example "inpNUMBER" "inpEMAIL" etc. please help here is a code Code: inputValue = scriptletContext.getLocal("inputVal"); inputType = scriptletContext.getLocal("inputTyp"); //scriptletResult = inputType; switch (inputType) { case 'number': scriptletResult=("inpNUMBER",/^[-+]?\d+(\.\d+)?$/.test(inputValue)); //scriptletContext.put("inpNUMBER",/^[-+]?\d+(\.\d+)?$/.test(inputValue)); case 'email': scriptletResult=("inpEMAIL",/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(2([0-4]\d|5[0-5])|1?\d{1,2})(\.(2([0-4]\d|5[0-5])|1?\d{1,2})){3} \])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(inputValue)); //criptletContext.put("inpEMAIL",/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(2([0-4]\d|5[0-5])|1?\d{1,2})(\.(2([0-4]\d|5[0-5])|1?\d{1,2})){3} \])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(inputValue)); case 'string': scriptletResult=("inpALPHA",/^[a-z0-9]+$/.test(inputValue)); //scriptletContext.put("inpALPHA",/^[a-z0-9]+$/.test(inputValue)); case 'ip': scriptletResult=("inpIP",/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)+$/.test(inputValue)); //scriptletContext.put("inpIP",/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)+$/.test(inputValue)); default: scriptletContext.put("errors",inputType) }; I'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. This has always puzzled me: Code: foo="bar"; switch(foo) { case "bar": { alert("a"); } case 123: { alert("b"); } } "a" is displayed because foo=="bar", but even if execution continues to the next block, surely "b" shouldn't be displayed because foo!=123? Does anyone know what the logic behind this is? 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> hi everybody, i'm using JSE client-side site search engine to search in my page.. and this is the code: Code: var cookies = document.cookie; var p = cookies.indexOf("d="); if (p != -1) { var st = p + 2; var en = cookies.indexOf(";", st); if (en == -1) { en = cookies.length; } var d = cookies.substring(st, en); d = unescape(d); } var od = d; var m = 0; if (d.charAt(0) == '"' && d.charAt(d.length - 1) == '"') { m = 1; } var r = new Array(); var co = 0; if (m == 0) { var woin = new Array(); var w = d.split(" "); for (var a = 0; a < w.length; a++) { woin[a] = 0; if (w[a].charAt(0) == '-') { woin[a] = 1; } } for (var a = 0; a < w.length; a++) { w[a] = w[a].replace(/^\-|^\+/gi, ""); } a = 0; for (var c = 0; c < s.length; c++) { pa = 0; nh = 0; for (var i = 0; i < woin.length; i++) { if (woin[i] == 0) { nh++; var pat = new RegExp(w[i], "i"); var rn = s[c].search(pat); if (rn >= 0) { pa++; } else { pa = 0; } } if (woin[i] == 1) { var pat = new RegExp(w[i], "i"); var rn = s[c].search(pat); if (rn >= 0) { pa = 0; } } } if (pa == nh) { r[a] = s[c]; a++; } } co = a; } if (m == 1) { d = d.replace(/"/gi, ""); var a = 0; var pat = new RegExp(d, "i"); for (var c = 0; c < s.length; c++) { var rn = s[c].search(pat); if (rn >= 0) { r[a] = s[c]; a++; } } co = a; } function return_query() { document.jse_Form.d.value = od; } function num_jse() { document.write(co); } function out_jse() { if (co == 0) { document.write('Your search did not match any documents.<p>Make sure all keywords are spelt correctly.<br>Try different or more general keywords.'); return; } for (var a = 0; a < r.length; a++) { var os = r[a].split("^"); if (bold == 1 && m == 1) { var br = "<b>" + d + "</b>"; os[2] = os[2].replace(pat, br); } if (include_num == 1) { document.write(a + 1, '. <a href="', os[1], '">', os[0], '</a><br>', os[2], '<p>'); } else { document.write('<a href="', os[1], '">', os[0], '</a><br>', os[2], '<p>'); } } } i got it from http://www.javascriptkit.com/script/...se/index.shtml but, in turkish alphabet the uppercase of "i" is "İ" with a dot.. and the lowercase of "I" is "ı" without a dot.. when i use the code above, it doesn't find "TEFSİR" if the user type it in lowercase as "tefsir".. also doesn't find "Bayraklı" if the user type it all in uppercase as "BAYRAKLI" is there a way to make this work? Urghh I've always done it this way but it's nagging me. Is there a better way of checking if a value is equal to 1 or 2 or 3 than doing it this way. Code: if(var === Cat || var === Dog || var === Chicken || var === Frog) Not working code ^ lol Cheers guys I put the jquery script into my subdirectory. In the header which one is correct: Code: <script type="text/javascript" src="../jquery/jquery.js"></script> or Code: <script src="../jquery/jquery.js"></script> And there is this code: do I put this in the body and enclose it with the <script>tag? Code: $(function(){ // set interval for 5 minutes setInterval(function(){ $.ajax({url: "keep-alive.php"}); }, 300000); }); can I have a function and a variable be the same name in an object for instance Code: function someObject(){ this.canDoSomething;//a boolean variable function canDoSomething(){ //set this.canDoSomething; return this.canDoSomething; } } or will this be a naming conflict? thanks I found this "game" that helps you practice regexp. I'm stuck on this one: Was wondering if someone could help me quickly, i'm have a strange issue with a slideshow i have built in javascript. The slideshow works fine until you add any other image onto the page like a banner or anything. As soon as you do that when you click next on the slideshow that image or banner with change to the next picture instead of the desired image if that makes any sense... Would appreciate any help, thank you! here is the link to my practice website, so you can see what is going on pretty new to all of this.. http://dpetersen.net46.net/advancedw...l.html?agree=0 using jquery and cookie plugin. i made a popup window. when the user clicks on a check box the window closes, forwards them to a new page, and then sets a cookie. i need it so that when they go back to the original page (where the popup came from) if the browser detects the cookie then the popup does not occur. I do not know why this does not work because when I alert the value of the cookie out, it gives me the correct number. something must be wrong in my logic ? code on the base page. Code: <script type="text/javascript"> var test123 = $.cookie('FBCheck'); if ( test123 != 1212){ function popup(Site) { window.open(Site,'PopupName','toolbar=no,statusbar=no, location=no,scrollbars=no,resizable=no,width=350,height=500') } } </script> code on popup (both files are in same directory) Code: $(document).ready(function() { $("#Cbox").click(function() { window.open ("http://www.google.com", "Google"); window.close(); $.cookie('FBCheck', '1212', {expires: 365, path: '/'}); }); }); The jquery source is installed as is the plugin. Thanks so much for your help in advance! Hi, Ever seen on the iphone where you have to slide the slider across the screen to unlock it? I have a duplicate of this using javascript but no matter what I try I cannot make it redirect. I want the page to be redirected after the slider has gone to the other side. Heres the HTML Code: <!DOCTYPE html> <head> <meta charset='UTF-8'> <title>Slide To Unlock</title> <link rel='stylesheet' href='css/style.css'> <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'></script> <script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js'></script> <script src='js/slidetounlock.js'></script> </head> <body> <div id="page-wrap"> <div id="well"> <h2><strong id="slider"></strong> <span>slide to unlock</span></h2> </div> </div> </body </html> And the javascript Code: $(function() { $("#slider").draggable({ axis: 'x', containment: 'parent', drag: function(event, ui) { if (ui.position.left > 550) { $("#well").fadeOut(); } else { // Apparently Safari isn't allowing partial opacity on text with background clip? Not sure. // $("h2 span").css("opacity", 100 - (ui.position.left / 5)) } }, stop: function(event, ui) { if (ui.position.left < 551) { $(this).animate({ left: 0 }) } } }); // The following credit: http://www.evanblack.com/blog/touch-slide-to-unlock/ $('#slider')[0].addEventListener('touchmove', function(event) { event.preventDefault(); var el = event.target; var touch = event.touches[0]; curX = touch.pageX - this.offsetLeft - 73; if(curX <= 0) return; if(curX > 550){ $('#well').fadeOut(); } el.style.webkitTransform = 'translateX(' + curX + 'px)'; }, false); $('#slider')[0].addEventListener('touchend', function(event) { this.style.webkitTransition = '-webkit-transform 0.3s ease-in'; this.addEventListener( 'webkitTransitionEnd', function( event ) { this.style.webkitTransition = 'none'; }, false ); this.style.webkitTransform = 'translateX(0px)'; }, false); }); Hi guys, just a quick question about a line break in JavaScript, where would I do it? If you see I have two math operators here and want them to be on two separate lines, were do I put the line break? Thanks Code: <!doctype html> <head> </head> <body> <script type="text/javascript"> var apples = 4+76; document.write(apples); var multiple = 54*11; document.write(multiple); </script> </body> </html> I have a simple issue that I cannot fix. The code bellow, is a while-loop with RGB color. It displays the word Hello 10 times id 10 different colors. The problem is I cannot get the correct colors displayed. I want the first Hello to be red and end up green in the last one. For some reason I cannot get the color combination correct, even after I put 255 for red and 192 for green. Can you please have a look and tell me what am I doing wrong? Thanks in advance 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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Project 4 - Exercise 10</title> </head> <body> <script language="JavaScript"> var r = 254; var g = 254; var b = 125; for (i=1; i <= 10; i++) { document.write ("<font size=7 color = rgb(" + i + "," + g + ", "+b+")> Hello <br>"); } </script> </body> </html> i have a program where a user enters a temperature in farenheit and the program converts it to celcius. below is my code: Code: <html> <head> <title>JavaScript Assignment 4 Part 1</title> </head> <body> <h2>Welcome to the Temperature Calculator!!</h2> <script type="text/javascript"> var fTemp; var number1; var cTemp; fTemp = window.prompt( "Please enter temperature in Farenheit:", "0" ); number1 = parseInt( fTemp ); cTemp = (5/9) * (number1 - 32); document.writeln("The corresponding temperature in Celcius is: " + cTemp); </script> </body> </html> what i cant figure out is how to round off the temperature in celcius so that it doesnt display something like 26.666666666667 i tried putting math.round in "cTemp = (5/9) * (number1 - 32);" but when i do my program doesnt work any advice on how to go about doing this? thanks |