JavaScript - Unit Conversion Case Switch Problem
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. 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? 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) }; 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. 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! -------- 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. 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 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? Greetings, I am new to these forums, and am wrapping up a JavaScript class for the year. I am in desperate need of help (which I usually obtain from my Instructor, but she is away from the office today) with my Tutorial 12, Case Problem 1 : New Perspectives JavaScript and AJAX 2nd Edition( by Patrick Carey). I am running xampp as my testing environment, and using Dreamweaver CS4 to write my code. I've completed the code work, however I am having issues with Step 6 code. 6) Add the retrieveOrders() function. Within this function, do the following: a. Create variables named user, pwd, sButton, and orderHistory to refrence the elements on the Web page with ID values of userID, pwd, submitButton, and orderhistory, respectively. b. Add and event handler to the sButton object that runs when the button is clicked. Steps c through e should all be done within this event handler. c . Create variables named userValue and pwdValue equal to the values entered into the user and pwd input boxes. respectively. d. If userValue and pwdValue both are non-empty, create a request object named reqOrders. Using the get method, open the following URL with the request object /cgi-bin/wworders.pl?user=userValue&pwd=pwdValue where userValue and pwdValue are the values of userValue and pwdValue variables, respectively. e. Send the request and then wait for a complete and error-free response from the server. When the response arrives, store the text of the response in the orderHistory object on the Web page. --- Here is the code from my html file and my .js file(s) NOTE: I had to copy the addEvent function from wwlibrary.js to eliminate an error of addEvent not defined. Code: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <!-- New Perspectives on JavaScript, 2nd Edition Tutorial 12 Case Problem 1 Wizard Works Order History Author: Rachael Magnuson Date: May 11th, 2010 Filename: orders.htm Supporting files: getorders.js, wwlibrary.js, wwlogo.jpg, wworders.pl, wwstyles.css --> <title>Check Your Order History</title> <link href="wwstyles.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="wwlibrary.js"></script> <script type="text/javascript" src="getorders.js"></script> </head> <body> <div id="heading"><img src="wwlogo.jpg" alt="Wizard Works" /></div> <div id="links"> <ul> <li><a href="sblogger.htm">HOME PAGE</a></li> <li class="newgroup"><a href="#">Firecrackers</a></li> <li><a href="#">Fountains</a></li> <li><a href="#">Cones</a></li> <li><a href="#">Rockets</a></li> <li><a href="#">Sparklers</a></li> <li><a href="#">Assortments</a></li> <li class="newgroup"><a href="#">Online Store</a></li> <li><a href="#">Shopping Cart</a></li> <li><a href="#">View Your Account</a></li> <li><a href="#">Track Orders</a></li> <li><a href="#">Order History</a></li> <li class="newgroup"><a href="#">FAQ</a></li> <li><a href="#">Tech Support</a></li> <li><a href="#">Safety Manuals</a></li> <li><a href="#">Customer Service</a></li> <li><a href="#">Contact Us</a></li> <li class="newgroup"><a href="#">About Us</a></li> <li><a href="#">WW History</a></li> <li><a href="#">Fireworks Gallery</a></li> <li><a href="#">Fireworks Video</a></li> <li><a href="#">Reviews</a></li> <li><a href="#">Testimonials</a></li> </ul> </div> <div id="main"> <h1>Retrieve Your Order History</h1> <p id="inputPara"> <label id="userlabel" for="userid">Enter your user ID</label> <input type="text" id="userid" name="userid" /> <label id="pwdlabel" for="pwd">Enter your password</label> <input type="password" id="pwd" name="pwd" /> <input type="button" id="submitButton" value = "View Orders" /> </p> <div id="orderhistory"></div> </div> </body> </html> Code: /* New Perspectives on JavaScript, 2nd Edition Tutorial 12 Case Problem 1 Filename: wwlibrary.js Functions List: addEvent(object, evName, fnName, cap) Adds an event handler to object where object is the object reference, evName is the name of the event, fnName is the reference to the function, and cap specifies the capture phase. XMLHttpRequest() Creates a custom XMLHttpRequest object for IE browsers that do not support the native XMLHttpRequest object (chiefly IE5 and IE6) */ function addEvent(object, evName, fnName, cap) { if (object.attachEvent) object.attachEvent("on" + evName, fnName); else if (object.addEventListener) object.addEventListener(evName, fnName, cap); } if (typeof XMLHttpRequest === "undefined") { XMLHttpRequest = function() { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) { try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) { try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { throw new Error("Unable to create your request object"); } } } } } } Code: /* New Perspectives on JavaScript, 2nd Edition Tutorial 12 Case Problem 1 Author: Rachael Magnuson Date: May 11th, 2010 Filename: getorders.js Functions List: retrieveOrders() Retrieves the orders from the Web server and displays the HTML code in the orderhistory section of the document */ addEvent(window, "load", retrieveOrders, false); function addEvent(object, evName, fnName, cap) { if (object.attachEvent) object.attachEvent("on" + evName, fnName); else if (object.addEventListener) object.addEventListener(evName, fnName, cap); } function retrieveOrders(){ var user = document.getElementById("userid"); var pwd = document.getElementById("pwd"); var sButton = document.getElementById("submitButton"); var orderHistory = document.getElementById("orderhistory"); sButton.onclick = function() { var userValue =escape(user.value); var pwdValue = escape(pwd.value); if (userValue && pwdValue != ""){ var reqOrders = new XMLHttpRequest(); var reqURL ="/cgi-bin/wworders.pl?skey=" + userValue&pwdValue; reqOrders.open("GET", reqURL); reqOrders.send(null); reqOrders.onreadystatechange=function() { if (this.readyState ==4) { if (this.status == 200) { orderHistory.innerHTML = this.responseText; } } } } } } Hi all, First of all thanks for everyone who responds to me. I appreciate it. Here is my problem. I have a HTML form containing two text box controls in it and a submit button. When a user enters information in those two textboxes and click on submit, the information is sent to a function in Javascript. In the javascript, the information from those textboxes is stored in a javascript variable. The problem is as follows: When I am inputting string text in the html text boxes and in the javascript when I am trying to print those values, it is giving me out an error saying NaN. However when i input integer values in the text boxes it is printing those numbers. Is there a conversion that I have to do for the string to be printed. I am new to Javascript and need your help. This is a basic code of Javascript. Below is the code that I have. Thanks in advance for your help. <html> <script type = "text/javascript"> function square(form) { var test = form.value1.value; window.alert(+test); var point = document.test.value1.value; pointcon = point.toString(); window.alert("nice"); window.alert(+pointcon); var point2 = eval(document.test.value2.value); var point3 = point + point2; alert(point3); } </script> <head> <body> <form name = "test"> First name: <input type="text" name = "value1" value1 = ""/><br /> Last name: <input type="text" name = "value2" value2 = ""/> <input type = "button" value = "Submit" onClick="square(this.form)"/> </form> </body> </html> Hello, I get Result of expression 'document.ConverTable' [undefined] is not an object. with the code below, and would like some help finding out what the problem is. Thanks! Code: ... <head> <script type="text/javascript"> function calc(val,factor,putin) { if (val == "") { val = "0" } evalstr = "document.ConverTable."+putin+ ".value = " evalstr = evalstr + val + "*" + factor eval(evalstr) } </script> </head> <body> ... Kg: <input size="10" onkeyup="calc(this.value,2.2046,'clbs')"> Pounds: <input name="clbs" size="10"> ... </body> 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 all -- I realize this is probably pretty simple, but it's been a while since I did any Javascripting, and things have changed a great deal. My apologies if I sound a bit clueless. I need to create a conversion tool. On one side of the tool are 4 form boxes. On the other, just text (not in form boxes). Under the covers, I have formulas for converting the numbers -- mostly basic math functions. So, the user types in numbers, clicks convert and the text changes. For some reason, I'm having a hard time getting this to go. How can I get the results of these calculations to show up as text within a DIV tag and not inside a form element? There are lots of examples of getting these calculations to appear within form boxes, but not within DIVs. Any examples would be greatly appreciated. This page is already using the Dojo toolkit for some other functionality, is this something I could leverage here to build my Javascript? Thanks in advance for your patience. I am trying to make a unit converter with two dropdown boxes, two textfields and a button. I want to enter a number into the first textfield, select a unit option, then select another appropriate unit option based on the first selection, press the button and get the result in the second textfield. What would be the best approach for this. So far I have: <html> <head> <script type="text/javascript"> function convertUnit () { // convert pound to kilogram document.unitForm.toField.value = document.unitForm.fromField.value / 2.2; // convert kilogram to pound document.unitForm.toField.value = document.unitForm.fromField.value * 2.2; // convert inch to centimeter document.unitForm.toField.value = document.unitForm.fromField.value / 2.54; // convert centimeter to inch document.unitForm.toField.value = document.unitForm.fromField.value * 2.54; } </script> </head> <body style="background-color:lightgray"> <form action="" name="unitForm"> <input type="text" name="fromField" onfocus="this.form.fromField.value=''; style.background='lightyellow';" onblur="style.background='white';" /> <select name="fromList" > <option value="" selected="selected">Unit</option> <option id="fromPound" value="2.2">lb</option> <option id="fromKilogram" value="1.0">kg</option> <option id="fromInch" value="1.0">in</option> <option id="fromCentimeter" value="2.54">cm</option> </select> <input type="button" value="Convert" onclick="convertUnit()" /> <input type="text" name="toField" readonly="readonly" /> <select name="toList"> <option value="" selected="selected">Unit</option> <option name="toKilogram" id="toKilogram" value="1.0">kg</option> <option name="toPound" id="toPound" value="2.2">lb</option> <option name="toCentimeter" id="toCentimeter" value="2.54">cm</option> <option name="toInch" id="toInch" value="1.0">in</option> </select> <input type="reset" value="Reset" /> </form> </body> </html> Dear Experts Var str="this is a string" I want to know how to replace this with Uppercase while using regular expression. Please help Code: var areas = { "The Plains of CASCADIAN": { yMin: 0, yMax: 20, xMin: 0, xMax: 24 }, "The Forests of BELGROS": { yMin: 0, yMax: 34, xMin: 24, xMax:50 }, "Bewitched VOLRAP": { yMin: 0, yMax: 42, xMin: 50, xMax:100 }, "The Moutains of MELDROSS": { yMin: 26, yMax: 52, xMin: 0, xMax: 48 }, "The Moutains of OLAP": { yMin: 49, yMax: 68, xMin: 0, xMax: 48 }, "The Swamps of NEMBRESS": { yMin: 54, yMax: 90, xMin: 44, xMax: 100 }, "The Great Wood of OLKLEMPT": { yMin: 62, yMax: 100, xMin: 32, xMax: 100 }, "Dark Forests of MURLAP": { yMin: 60, yMax: 100, xMin: 0, xMax: 42 }, "Imperial MANTRIOCK": { yMin: 22, yMax: 58, xMin: 44, xMax:100 } } How would you reffer to the areas with a javascript if statment or case? Hi everyone, I've started a course on web design and I'm busy with a assignment on Javascript. I need to make a contact list which I'm nearly done with but I'm stuck with one bit, validating select lists, I want to do it using a case construct but I'm not sure how cause mine doesn't want to work. Will someone please help me? Code: case "email": var emailRegExp = /[a-z0-9]/i; /* Should contain at least 1 letter and can have numbers */ var email2RegExp = /[@]/; /* There has to be a @ character */ var email3RegExp = /[.]/; /* Should contain at least 1 . */ var email4RegExp = /[ ]/; /* Can not have any spaces */ if (emailRegExp.test(fld.value) == true && email2RegExp.test(fld.value) == true && email3RegExp.test(fld.value) == true && email4RegExp.test(fld.value) == false) { fld.valid = true; } break; case "day": /* Day of birth, Select list */ if (dd.value="no") == false; { fld.valid = true; } break; case "month": /* Month of birth, Select list */ if (mm.value="no") == false; { fld.valid = true; } break; case "year": /* Year of birth, Select list */ if (yyyy.value="no") == false; { fld.valid = true; } break; case "select_list": if (not(select_list.value=no)) { fld.valid = true; } break; } } function validate(frm) { for (i = 0; i < frm.length - 1; i++) { ValidateField(frm.elements[i]) } } function validation(frm) { var validation_text = ""; if (frm.fname.valid == false) { validation_text += "First Name Field is either empty or incorrect, only letters, spaces and hyphens allowed.\n\n" } if (frm.lname.valid == false) { validation_text += " Last Name Field is either empty or incorrect, only letters, spaces and hyphens allowed.\n\n" }0 if (frm.housename.valid == false) { validation_text += "Your House name Field is either empty or incorrect, letters, spaces and hyphens allowed.\n\n" } if (frm.streetname.valid == false) { validation_text += "Your Street name Field is either empty or incorrect, letters, spaces and hyphens allowed.\n\n" } if (frm.townname.valid == false) { validation_text += "Your Town name Field is either empty or incorrect, letters, spaces and hyphens allowed.\n\n" } if (frm.county.valid == false) { validation_text += "Your County Field is either empty or incorrect, letters, spaces and hyphens allowed.\n\n" } if (frm.postcode.valid == false) { validation_text += "Postcode Field is either empty or incorrect, Capital letters and numbers allowed.\n\n" } if (frm.teleph.valid == false) { validation_text += "Telephone number Field is either empty or incorrect, only numbers allowed.\n\n" } if (frm.email.valid == false) { validation_text += "Email Field is either empty or incorrect, letters, numbers, @, . , and no spaces allowed.\n\n" } if (frm.dd.valid == false) { validation_text += "You have not selected your Day Of Birth. Please use the list. \n\n" } if (frm.mm.valid == false) { validation_text += "You have not selected your Month Of Birth. Please use the list. \n\n" } if (frm.yyyy.valid == false) { validation_text += "You have not selected your Year Of Birth. Please use the list. \n\n" } if (frm.select_list.valid == false) { validation_text += "You have not selected your best form of contact. Please use the list. \n\n" } if (validation_text == "") { validation_text += "Thank you for entering your details!" alert(validation_text); return true; } else { alert(validation_text) return false; } } </script> </head> <body> <form name="ContactList" method="post" action="mailto:lourens.erasmus@btinternet.com" onSubmit="validate(this); return validation(this);"> <table border="0" align="center" cellspacing="5" cellpadding="5" width="600"> <tr> <th align="center" colspan="2"> <h2> <b>Contact List</b></h2> </th> </tr> <tr> <td> First Name </td> <td> <input type="text" name="fname"> </td> </tr> <tr> <td> Last Name </td> <td> <input type="text" name="lname"> </td> </tr> <tr> <td> House Name or Number </td> <td> <input type="text" name="housename"> </td> </tr> <tr> <td> Street Name </td> <td> <input type="text" name="streetname"> </td> </tr> <tr> <td> Town </td> <td> <input type="text" name="townname"> </td> </tr> <tr> <td> County </td> <td> <input type="text" name="county"> </td> </tr> <tr> <td> Postcode </td> <td> <input type="text" name="postcode"> </td> </tr> <tr> <td> Telephone </td> <td> <input type="text" name="teleph"> </td> </tr> <tr> <td> Email Address </td> <td> <input type="text" name="email"> </td> </tr> <tr> <td> Date Of Birth </td> <td> <select name="dd"> <option value="no">DAY</option> <option value="1">01</option> <option value="2">02</option> <option value="3">03</option> <option value="4">04</option> <option value="5">05</option> <option value="6">06</option> <option value="7">07</option> <option value="8">08</option> <option value="9">09</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <select name="mm"> <option value="no">MONTH</option> <option value="Jan">January</option> <option value="Feb">February</option> <option value="Mar">March</option> <option value="Apr">April</option> <option value="May">May</option> <option value="Jun">June</option> <option value="Jul">July</option> <option value="Aug">August</option> <option value="Sept">September</option> <option value="Oct">October</option> <option value="Nov">November</option> <option value="Dec">December</option> </select> <select name="yyyy"> <option value="no">YEAR</option> <option value="50">1950</option> <option value="51">1951</option> <option value="60">1952</option> <option value="60">1953</option> <option value="60">1954</option> <option value="60">1955</option> <option value="60">1956</option> <option value="60">1957</option> <option value="60">1958</option> <option value="60">1959</option> <option value="60">1960</option> <option value="60">1961</option> <option value="60">1962</option> <option value="60">1963</option> <option value="60">1964</option> <option value="60">1965</option> <option value="60">1966</option> <option value="60">1967</option> <option value="60">1968</option> <option value="60">1969</option> <option value="60">1970</option> <option value="60">1971</option> <option value="60">1972</option> <option value="60">1973</option> <option value="60">1974</option> <option value="60">1975</option> <option value="60">1976</option> <option value="60">1977</option> <option value="60">1978</option> <option value="60">1979</option> <option value="60">1980</option> <option value="60">1981</option> <option value="60">1982</option> <option value="60">1983</option> <option value="60">1984</option> <option value="60">1985</option> <option value="60">1986</option> <option value="60">1987</option> <option value="60">1988</option> <option value="60">1989</option> <option value="60">1990</option> <option value="60">1991</option> <option value="60">1992</option> <option value="60">1993</option> <option value="60">1994</option> <option value="60">1995</option> <option value="60">1996</option> <option value="60">1997</option> <option value="60">1998</option> <option value="60">1999</option> <option value="60">2000</option> </select> </td> </tr> <tr> <td> Best Time to Call </td> <td> <input type="radio" name="best" value="Morning">Morning<br> <input type="radio" name="best" value="Afternoon" checked>Afternoon<br> <input type="radio" name="best" value="Evening">Evening </td> </tr> <tr> <td> Best Form of Contact </td> <td> <select name="select_list"> <option value="no">-Please Select-</option> <option value="Telephone">Telephone</option> <option value="Post">Post</option> <option value="Email">Email</option> </select> </td> </tr> <tr> <td align="center" colspan="2"> <input type="submit" value="Submit"> </td> </tr> </table> </form> </body> </html> Wrote this code out and it doesnt function correctly but I cannot see nefin wrong with it: <script type="text/javascript"> var choice; var startTag; var endTag; var validInput; var listType; choice = window.prompt("Select a list style:\n" + "1 (numbered), 2 (lettered), 3 (roman)", "1"); switch (choice) { case "1": startTag = "<ol>"; endTag = "</ol>"; listType = "<h1>Numbered List</h1>"; break; case "2": startTag = "<ol style = \"list-style-type: upper-alpha\">"; endTag = "</ol>"; listType = "<h1>Lettered List</h1>"; break; case "3": startTag = "<ol style = \"list-style-type: upper-roman\">"; endTag = "</ol>"; listType = "<h1> Roman Numbered List</h1>"; break; default: validInput = false; } if ( validInput == true ) { document.write(listType + startTag); for (var i = 1; i <= 3; ++i) document.write("<li>List Item " + i + " </li>" ); document.write(endTag); } else document.write("Invalid choice: " + choice); </script> I am having trouble with the following: Code: <script language="javascript" > function premium_calculator() { var val = document.getElementById('user_input').value; var state = document.getElementById('user_state').value; alert ( state ); // if (state=1) // alert ("QLD"); // else // if (state=2) // alert ("NSW"); // else // alert ("ACT"); switch (state) { case 1: alert ("QLD"); break: case 2: alert ("NSW"); break; case 3: alert ("ACT"); break; } document.getElementById('val_100_1').innerHTML =0; document.getElementById('val_250_1').innerHTML = 12; document.getElementById('val_500_1').innerHTML = 13; document.getElementById('val_1000_1').innerHTML = 14; } the above code produces nothing, no alert messages and no returned elements. can be seen here http://www.scubaservice.com.au/calculation-test-2.html If I comment out the switch statement entirely and use the if statement; the first alert statement will produce a 1,2 or 3 depending on input but the second alert is always "QLD". There are several calculations for each of the returned values and these will be different depending on the state selected. The basis for the calculations work on their own ie for 1 state. http://www.scubaservice.com.au/calculation-test.html Any help to get this working would be apreciated. Hi, am new to Java, Jquery and Java Script and I am finding my way through recently... I have this HTML code Code: <html:text styleClass="ui-inputText" size="12" styleId="fromDate" property="fromDate" name="HomePageForm" readonly="readonly" /> <script> initDatePicker("fromDate"); </script> I want to perform this action using JS. This will create a text-box with a calender affixed to it if used in Plain HTML... This is the initdatepicker function Code: function initDatePicker(dateFieldId){ var format = '<%=ctx.getDateFormat()%>'; if (format == "yyyy-MM-dd"){ format= "yy-mm-dd"; }else if (format == "MM/dd/yyyy"){ format= "mm/dd/yy"; }else if (format == "dd-MMM-yyyy"){ format= "dd-M-yy" } $("#"+dateFieldId).datepicker({ showOn: 'button', buttonImage: 'include/images/icons/calendar.png', buttonImageOnly: true, changeMonth: false, changeYear: false, buttonText: 'Select date' , dateFormat: format }); } I have done a few things, but, could not get the result I need... Code: cellIndex++; var cellObj=$('#genericRules tr:eq('+index+') td:eq('+cellIndex+')'); cellObj.html(''); var table = document.getElementById("genericRules"); var rowElem = table.rows[index]; var cell = rowElem.insertCell(3); var txtInp = getTextField(indexName,index,'8'); cell.appendChild(txtInp); var dateImg = getImage(index); cell.appendChild(dateImg); cell.align="center"; initDatePicker(indexName + '['+index+'].'+name+'from'); function getTextField(indexName, index, size) { //, maxlength var txtInp = document.createElement('input'); txtInp.setAttribute('type', 'text'); txtInp.setAttribute('class', 'ui-inputText'); txtInp.setAttribute('indexed', 'true'); txtInp.setAttribute('name', indexName + '['+index+'].'+name+'from'); txtInp.setAttribute('id', indexName + '['+index+'].'+name+'from'); txtInp.setAttribute('size',size); txtInp.className = "ui-inputText"; txtInp.name=indexName+'['+index+'].'+name; txtInp.indexed ='true'; return txtInp; } function getImage(index){ var image = document.createElement("img"); image.src = "<%=request.getContextPath()%>/include/images/icons/calendar.png"; image.setAttribute('class', 'inputCalendar'); image.className = "inputCalendar"; image.name = "imgDatevalue"+index; image.id = "imgDatevalue"+index; return image; } My application is now showing me the image but, am not able to get the calender when i click on it.. I need help on this thing... Please try to provide me with soem intel... |