JavaScript - Trouble With Javascript If, Else Statements
I'm a little new to Javascript so I apologise if this is an easily resolved problem.
This is my Javascript code: Code: function display(){ if(document.getElementById('one').style.display="none"){ document.getElementById('one').style.display="block"; } else if(document.getElementById('one').style.display="block"){ document.getElementById('two').style.display="block"; } else{ document.getElementById('three').style.display="block"; } } This is my HTML: Code: <html> .... <style> #one,#two,#three { display:none; } </style> .... <ul> <li id="one">1</li> <li id="two">2</li> <li id="three">3</li> <li id="click" onclick="display()">+</li> </ul> The idea is when I click the list item 'click' the display() function will be called and make list item 'one' appear. If list item 'one' is already visible however, list item 'two' will appear, etc. When I click it, list item one appears fine as it should, but if I click it again list item two does not appear, and I can't work out why. I could really do with some help, thank you in advance! Similar TutorialsCode: top.window.moveTo(0, 0); if (document.all) { top.window.resizeTo(screen.availWidth, screen.availHeight); } else if (document.layers || document.getElementById) { if (top.window.outerHeight < screen.availHeight || top.window.outerWidth < screen.availWidth) { top.window.outerHeight = screen.availHeight; top.window.outerWidth = screen.availWidth; } } function gcd(a, b) { return (b === 0) ? a : gcd(b, a % b); } var i = 0; var BrowserDetect = { init: function () { this.browser = this.searchString(this.dataBrowser) || "An unknown browser"; this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version"; this.OS = this.searchString(this.dataOS) || "an unknown OS"; }, searchString: function (data) { for (; i < data.length; i + 1) { var dataString = data[i].string, dataProp = data[i].prop; this.versionSearchString = data[i].versionSearch || data[i].identity; if (dataString) { if (dataString.indexOf(data[i].subString) !== -1) { return data[i].identity; } } else if (dataProp) { return data[i].identity; } } return data[i].identity; }, searchVersion: function (dataString) { var index = dataString.indexOf(this.versionSearchString); if (index === -1) { return parseFloat(dataString.substring(index + this.versionSearchString.length + 1)); } }, dataBrowser: [ { string: navigator.userAgent, subString: "Chrome", identity: "Chrome" }, { string: navigator.userAgent, subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb" }, { string: navigator.vendor, subString: "Apple", identity: "Safari", versionSearch: "Version" }, { prop: window.opera, identity: "Opera" }, { string: navigator.vendor, subString: "iCab", identity: "iCab" }, { string: navigator.vendor, subString: "KDE", identity: "Konqueror" }, { string: navigator.userAgent, subString: "Firefox", identity: "Firefox" }, { string: navigator.vendor, subString: "Camino", identity: "Camino" }, { string: navigator.userAgent, subString: "Netscape", identity: "Netscape" }, { string: navigator.userAgent, subString: "MSIE", identity: "Explorer", versionSearch: "MSIE" }, { string: navigator.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv" }, { string: navigator.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla" } ], dataOS : [ { string: navigator.platform, subString: "Win", identity: "Windows" }, { string: navigator.platform, subString: "Mac", identity: "Mac" }, { string: navigator.userAgent, subString: "iPhone", identity: "iPhone/iPod" }, { string: navigator.platform, subString: "Linux", identity: "Linux" } ] }; var version; if (dataString.indexOf(dataBrowser.versionSearch) !== -1) { version = parseFloat(string.indexOf(dataBrowser.versionSearch), 1); } else { version = parseFloat(string.indexOf(dataBrowser.identity), 1); } BrowserDetect.init(); if (dataBrowser.identity === "Chrome") { if (version >= 8) { document.location.replace("main/index.htm"); } else if (version >= 3) { document.location.replace("meh/index.htm"); } else { document.location.replace("http://www.browserchoice.eu/"); } } else if (dataBrowser.identity === "Safari") { if (version >= 5) { document.location.replace("main/index.htm"); } else if (version >= 3) { document.location.replace("meh/index.htm"); } else { document.location.replace("http://www.browserchoice.eu/"); } } else if (dataBrowser.identity === "Opera") { document.location.replace("http://www.google.com/"); } else if (dataBrowser.identity === "Firefox") { document.location.replace("http://www.google.com/"); } else if (dataBrowser.identity === "Mozilla") { document.location.replace("http://www.yahoo.com/"); } else if (dataBrowser.identity === "Explorer") { if (version >= 8) { document.location.replace("meh/index.htm"); } else { document.location.replace("http://www.browserchoice.eu/"); } } For some reason, this script was working before I put in the if statements, but after the if statements were placed in, it stopped auto maximizing as well, and no if statements were added around this. Does anyone know what the problem is? (It's supposed to redirect by browser to one of 3 sites based on how good they are) Hi, I believe this question has been asked by someone else before. However, it seems that the problem wasn't resolved. I'm having some trouble with the Switch Statements. My program runs without it so I know that the problem is here. I believe the logic is sound so it may be due to incorrect syntax. I will appreciate if someone could take a look at my code below and guide me in the right direction. Thank you. The purpose of this function is to create bars, and the length of the bars is determined by the value of the "percent" variable (which is working fine) in the For loop after the Switch statements. The variable, "partyType" contains any of the text strings, such as "I", "D", etc. Code: function createBar(partyType,percent){ var barText; switch(partyType){ case "D": barText="<td class='dem'></td>"; break; case "R": barText="<td class='rep'></td>"; break; case "I": barText="<td class='ind'></td>"; break; case "G": barText="<td class='green'></td>"; break; case "L": barText="<td class='lib'></td>"; break; default: document.write("hi"); } for(var i=1; i<percent; i++){ document.write(barText); } } } Writing Table Cells and Switch Statements I am to create a function and purpose is to write blank tables cells to make up horizontal bar. function will have 2 parameters=(partyType and percent partyType parameter stores variables of D,R,I,G or L percent parameter store percentage rounded to nearest integer so I am to make a switch and break statements /commands then have to create a For Loop in counter variable goes up from 1 through value of parmeter increments of 1 heres the code I created for this one Code: function createBar(partyType,percent){ // script element to create blank cells switch(partyType) { case "D": document.write("<td class='dem'></td>"); break; case "E": document.write("<td class='rep'></td>"); break; case "I": document.write("<td class='ind'></td>"); break; case "G": document.write("<td class='green'></td>"); break; case "L": document.write("<td class='lib'></td>"); break; } var barText = partyType for (i=0; i < percent; i++) { document.write(barText); So what improvements should I make? should my loop be before everything? Thanks Hey guys im new (nebwbie) here lol but know about some basic coding i got my code from http://www.javascriptkit.com/script/...megamenu.shtml that is my source i followed all the steps and everything step by step but this is what shows up on my page what am i doing wrong? or is there something wrong with the code? i already uploaded this on my site too jkmegamenu.css jkmegamenu.js I have been working on this code for a few days now. It is suppose to: 1. Remove the default values placed in the textarea. 2. Enter only numbers in the Phone Number field. 3. Verify that the passwords entered in the password fields are the same. 4. Verify everything is filled out, one of the radio buttons is selected and at least one of the check boxes are checked using a Submit() function as well as clear the fields using a Reset() function. I have the first two figured out and was able to get the password to verify once but can not get it to work again with any code. I am also unable to figure out a code that will call all these funtions together in the end to verify everything is filled out and not have the default words count as the field being filled. The idea of a default text is also kind of strange to me. I figured out how to remove the text entered as the value, but how do you get JavaScript to know that is the default and not an option to be used? 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>Registration</title> <!--Create a registration form, similar to what you may encounter when registering for an online Web site. Include three sections: Personal Information, Security Information, and Preferences. In the Personal Information section, add name, e-mail address, and telephone fields. Include default text in the name and e-mail text boxes, but write some code that removes the default text from each text box when a user clicks it. Write code for the telephone field that prevents users from entering any values except for numbers. In the Security Information section, add password and password confirmation fields. Write code that ensures that the same value was entered into both fields. Also add a security challenge question selection list and a security answer text box that the Web site will use to help identify a user in the event that he or she loses his or her password. The security challenge selection list should contain questions such as What is your mother's maiden name?, What is the name of your pet?, and What is your favorite color?. In the Preferences section, add radio buttons that confirm whether a user wants special offers sent to his or her e-mail address. Also, include check boxes with special interests the user may be interested in, such as entertainment, business, and shopping. Add submit and reset buttons that call submit() and reset() event handler functions when they are clicked. The submit() event handler function should ensure that the user has entered values into each text box, and that the values submitted are not the same as the default text. The submit() event handler function should also ensure that the user selects a security challenge question, selects a radio button to confirm whether he or she wants special offers sent to his or her e-mail address, and selects at least one interest check box. Submit the form to the FormProcessor.html script (there is a copy in your Cases folder for Chapter 5). Save the document as Registration.html. --> <script language="javascript" type="text/javascript"> // This JavaScript removes default values form field function doClear(theText) { if (theText.value == theText.defaultValue) { theText.value = "" } } // This JavaScript allows characters exept numbers function AcceptLetters(objtextbox) { var exp = /[^\D]/g; objtextbox.value = objtextbox.value.replace(exp,''); } // This JavaScript allows numbers only function AcceptDigits(objtextbox) { var exp = /[^\d]/g; objtextbox.value = objtextbox.value.replace(exp,''); } //This JavaScript confirms everything is filled out function confirmSubmit() { var submitForm = window.confirm("Are you sure you want to submit the form?"); if (document.registar[0].name.value == "Name" || document.registar[0].name.value == "" || document.registar[0].e_mail.value == "E-Mail Address" || document.registar[0].e_mail.value == "" || document.registar[0].phone.value == "" || document.registar[0].phone.value == "" || document.registar[0].password1.value == "" || document.registar[0].password2.value == "" || document.registar[0].sq_answer.value == "Question Answer") { window.alert("You must enter all fields above."); return false; } else return true; } </script> </head> <body> <h1>Registration Page</h1> <form name="registar " method="post" onsubmit="return confirmSubmit()"> <h3>Personal Information</h3> Name:<br /> <input type="text" name="name" value="Name" maxlength=10 id="letters" onFocus="doClear(this)" onkeyup="AcceptLetters(this)" /> <br /> E-Mail:<br /> <input type="text" name="email" value="E-mail Address" onFocus="doClear(this)" /> <br /> Phone Number:<br /> <input type="text" name="phoneNumber" maxlength=10 id="txttest" onFocus="doClear(this)" onkeyup="AcceptDigits(this)" /> <br /> <h3>Security Information</h3> Password:<br /> <input type="password" name="password1" /><br /> Confirm Password:<br /> <input type="password" name="password2" /><br /> <DIV ID="password_result"> </DIV> Security Question:<br /> <select id="selection"><br /> <option value=0>Please Choose One</option> <option value=1>What is your favorite food?</option> <option value=2>What is your Mother's maiden name?</option><br /> <option calue=3>What is your pets name?</option><br /> <option value=4>What is the name of your High School?</option><br /> </select><br /> Answer<br /> <input type="text" name="sq_answer" value="Question Answer" onFocus="doClear(this)" /><br /> <h3>Preferences</h3> Yes<input type="radio" name="confirmAnswer" value="Yes"/>No<input type="radio" name="answer" value="No" />Would you like any special offers sent to your E-mail address?<br /> <h5>Interests</h5> <input type="checkbox" name="interest" value="check"/>Entertainment<br /> <input type="checkbox" name="interest" value="check"/>Shopping<br /> <input type="checkbox" name="interest" value="check"/>Business<br /> <input type="checkbox" name="interest" value="check"/>Exercise<br /> <br /> <input type="submit" value="Submit"/> <input type="reset" value="Reset"/> </form> </body> </html> Hello, i have been trying to make a small one digit calculator, but i am having a lot of trouble with it..This is what i have so far. It will run each function individually, but if i try with all four sign functions, addition will only work....What am i doing wrong here? <!-- saved from url=(0014)about:internet --> <HTML> <HEAD> <TITLE>Page Title</TITLE> <SCRIPT language="JavaScript"> <!-- var n1 = -1; //1st operand of the expression -1 indicates n1 is empty var n2; //2st operand of the expression var startNew = true; var result; var operator; function readNumber(value) { if (n1 < 0) //n1 is empty { n1 = value; } else //n1 is not empty { n2 = value; } } function addition() { result = n1 + n2; //always deal with addition } function subtraction() { result = n1 - n2; //always deal with subtraction } function multiplication() { result = n1 * n2; //always deal with multiplication } function division() { result = n1 / n2; //always deal with division } function calculate_display() { //calculate the answer if (operator == '+') addition(); startNew = window.confirm(n1 + '+' + n2 + '=' + result + '\n' + ' start a new expression? '); if(startNew == true) //if ok is clicked { //clear n1 and n2 n1 = -1; n2 = -1; } { return; } if (operator == '-') subtraction(); startNew = window.confirm(n1 + '-' + n2 + '=' + result + '\n' + ' start a new expression? '); if(startNew == true) //if ok is clicked { //clear n1 and n2 n1 = -1; n2 = -1; } { return; } if (operator == '*') multiplication(); startNew = window.confirm(n1 + '*' + n2 + '=' + result + '\n' + ' start a new expression? '); if(startNew == true) //if ok is clicked { //clear n1 and n2 n1 = -1; n2 = -1; } { return; } if (operator == '-') division(); startNew = window.confirm(n1 + '/' + n2 + '=' + result + '\n' + ' start a new expression? '); if(startNew == true) //if ok is clicked { //clear n1 and n2 n1 = -1; n2 = -1; } { return; } } //--> </SCRIPT> </HEAD> <BODY> <form> <input type = "button" value="0" onclick="readNumber(0);"> <input type = "button" value="1" onclick="readNumber(1);"> <input type = "button" value="2" onclick="readNumber(2);"> <input type = "button" value="3" onclick="readNumber(3);"> <input type = "button" value="4" onclick="readNumber(4);"> <BR> <input type = "button" value="5" onclick="readNumber(5);"> <input type = "button" value="6" onclick="readNumber(6);"> <input type = "button" value="7" onclick="readNumber(7);"> <input type = "button" value="8" onclick="readNumber(8);"> <input type = "button" value="9" onclick="readNumber(9);"> <BR> <input type = "button" value="+" onclick="operator = '+';"> <input type = "button" value="-" onclick="operator = '-';"> <input type = "button" value="*" onclick="operator = '*';"> <input type = "button" value="/" onclick="operator = '/';"> <input type = "button" value="=" onclick="calculate_display();"> </form> I'm trying to make an xhtml form that validates itself through a javascript function. I have the form up but for some reason I can't get it to validate. I'm not even sure if I linked things correctly. Here's what I have: the xhtml file <?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> <script src="gas24.js" type="text/javascript"></script> <h2> Registration Form </h2> <title> Javascript Form Validation Homework </title> </head> <body> <table border=""> <form name="validation_form" method="post" onsubmit="return validate()"> <tr> <td> <t>Name: <input type="text" name="YourName" size="10" maxlength="10"/> </td> </tr> </br> <tr> <td> E-mail Address: <input type="text" name="YourEmail" size="10" maxlength="24"/> </td> </tr> </br> <tr> <td> Password: <input type="password" name="YourPassword" size="10" maxlength="10"/> </td> </tr> </br> <tr> <td> Re-Type Password: <input type="password" name="passwordConfirmed" size="10" maxlength="10"/> </td> </tr> </br> <tr> <td> Your Gender: <input type="radio" name="MaleBox" Value="Male"> Male <input type="radio" name="FemaleBox" Value="Female"> Female </td> </tr> </br> <tr> <td> Comments: <input type="text" name="Comments" size="100" maxlength="500" value=""/> </td> </tr> <tr> <td> <input type="submit" value="Submit"/> </td> </tr> </form> </table> <p></p> </body> </html> The javascript file: I've tried two things. This: <SCRIPT LANGUAGE="JavaScript"> function validation() { var x=document.forms["validation_form"]["YourName"].value; if (x==null || x=="") { alert("First name must be filled out"); return false; } } And this: function validation() if ( document.validation_form.YourName.value == "" ) { alert( "Please type your name."); valid = false; } if ( document.validation_form.YourPassword.value =! "document.validation_form.Confirm.value" ) { alert ( "Please confirm your password." ); valid = false; } I would greatly appreciate it if somebody could tell me what I'm doing wrong. Hi all, I am new to JS and usually learn by studying code posted online and modify it to have it do what I need. Recently, I used a totaling plugin for an online ordering form which does the below: item1 qty(user input text) * preset price = total price item2 qty(user input text) * preset price = total price item3 qty(user input text) * preset price = total price -------------------------------------------------------- grand total -------------------------------------------------------- The JS code which passes the grandTotal variable is as below: Code: function ($this){ // sum the total of the $("[id^=total_item]") selector var sum = $this.sum(); $("#grandTotal").text( // round the results to 2 digits "₹" + sum.toFixed(2) ); } The problem I have is the above grandTotal displays the final value when put into a table like below: Code: <td align="right" id="grandTotal"></td> But I am unable to make it work by passing it into a variable within the form fields. I would like to do something like this: Code: <input type="text" name="grandTotal" id="grandTotal" readonly="readonly" /> Can somebody please help me fix this? Any help will be greatly appreciated. Thank you. Im trying to figure out why this code won't work. Unsuccessfully. Sorry, didn't know how to use the "CODE" tag. <html> <head> <script type:"text/javascript"> var BGColor = prompt("Would you like the background of the page to be red, green, or blue?","") </script> </head> <body> <script type:"text/javascript"> if (BGColor == "red") { document.write('<body bgcolor= "red">The body of this page is RED. Press F5 to restart!') } else if (BGCOlor == "green") { document.write('<body bgcolor= "green">The body of this page is GREEN. Press F5 to restart!') } else if (BGColor == "blue") { document.write('<body bgcolor= "blue">The body of this page is BLUE. Press F5 to restart!') } </script> </body> </html> This may be a basic programing problem but I am writing a function to validate a form using a bunch of else-if statements and encounters a problem when I use nested if/else-if statements. It will not continue on to the next else-if, after it returns false. Code: // to check each entry on the form and alert user if entry is invalid. function checkform(){ var checkssn = /(\d{3})-(\d{2})-(\d{4})/; var checkphone = /(\d{3})-(\d{4})/; var checkname = /[a-zA-Z]+(\.|,|\s)*/; var checkzip = /(^967|^968)\d{2}(-\d{4})?$/; // check to see if user have selected an Election if (!document.f1.elections[0].checked && !document.f1.elections[1].checked && !document.f1.elections[2].checked && !document.f1.elections[3].checked) { window.alert("Please select an Election!") return false; // check to see if user entered a valid SSN } else if ( checkssn.test(document.f1.ssn.value) == false){ window.alert("[1]. Please enter a valid social security number in the format ddd-dd-ddd"); return false; // check to see if user entered a valid home telephone number or business telephone number }else if ( document.f1.home_phone.value == '' && document.f1.business_phone.value == '') { window.alert("[4]. Please enter a Home or Business telephone number!") return false; } else if ( document.f1.home_phone.value != ''){ if (checkphone.test(document.f1.home_phone.value) == false){ window.alert("[4]. Please enter a valid home phone number in the format ddd-ddd"); return false; } } else if ( document.f1.business_phone.value != ''){ if ( checkphone.test(document.f1.business_phone.value) == false){ window.alert("[4]. Please enter a valid business phone number in the format ddd-ddd"); return false; } // check to see if user entered a valid Name }else if ( checkname.test(document.f1.lastname.value) == false){ window.alert("[5]. Last Name can only consist of letters, periods(.), commas(,) and spaces"); return false; }else if ( checkname.test(document.f1.firstname.value) == false){ window.alert("[5]. First Name can only consist of letters, periods(.), commas(,) and spaces"); return false; The problem occurs when it validates the phone numbers. When a valid number is entered, it will not move to the next else-if statement to validate the name. It's been years since I program in Java/C, so I'm a bit rusty. Any help is appreciated. -Alex The issue I am having is with my sumAll function: Code: <script type="text/javascript"> /* <![CDATA[ */ function addNumbers() { a = parseInt(document.getElementById('txtFirst').value); b = parseInt(document.getElementById('txtSecond').value); c = parseInt(document.getElementById('txtThird').value); d = parseInt(document.getElementById('txtFourth').value); ansE = document.getElementById("Sum"); ansE.value = '$' + (a + b + c + d); x = (a + b + c + d); if ( x >= 100000) { document.getElementById('Bonus').value = '$' + 1200; } else if ( x > 50000 && x<100000) { document.getElementById('Bonus').value = '$' + 800; } else { document.getElementById('Bonus').value = '$' + 0; } if (document.getElementById('Blue').checked == true && document.getElementById('Gala').checked == true) { document.getElementById('Committee').value = '$' + 800; } else if (document.getElementById('Blue').checked == true && document.getElementById('Gala').checked == false) { document.getElementById('Committee').value = '$' + 350; } else if (document.getElementById('Blue').checked == false && document.getElementById('Gala').checked == true) { document.getElementById('Committee').value = '$' + 450; } else { document.getElementById('Committee').value = '$' + 0; } } function sumAll() { y = parseInt(document.getElementById('Bonus').value); z = parseInt(document.getElementById('Committee').value); total = document.getElementById("Total"); total.value = (y + z); } function funcCalc() { addNumbers(); sumAll(); } /* ]]> */ </script> I'm really new to this and I'm trying to figure out how to sum the two values from if statements. ParseInt is returning NaN. Before that, it was adding my results together as strings. Is there an easy way to add these together without creating a very complicated if statement to total these up? Thanks! 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, been using javascript for a while now, and wondering how else this could be coded to be more effective and to 'work'. The idea is that the user gets prompted, 'what is your birthday?' the user would put in 0121 or whatever their birthday is, as 01 = month and 21 = day. I'm sure you'll understand what I mean.... Code: <DOCTYPE html> <html> <script> var userAnswer = prompt("When is your birthday? Example: Jan 21st = 0121") </script> <head> </head> <body> <script> if(userAnswer >= 0101){ alert('You are Capricorn!') }; if(userAnswer >= 0120){ alert('You are Aquarius!') }; if(userAnswer >= 0219){ alert('You are Pisces!') }; if(userAnswer >= 0321){ alert('You are Aries') }; if(userAnswer >= 0420){ alert('You are Taurus') }; if(userAnswer >= 0521){ alert('You are Gemini!') }; if(userAnswer >= 0621){ alert('You are Cancer!') }; if(userAnswer >= 0723){ alert('You are Leo!') }; if(userAnswer >= 0823){ alert('You are Virgo!') }; if(userAnswer >= 0923){ alert('You are Libra!') }; if(userAnswer >= 1023){ alert('You are Scorpio!') }; if(userAnswer >= 1122){ alert('You are Sagittarius!') }; if(userAnswer >= 1222){ alert('You are Capricorn!') }; </script> </body> </html> Reply With Quote 01-18-2015, 10:01 AM #2 Mitchellwood101 View Profile View Forum Posts New to the CF scene Join Date Nov 2014 Posts 7 Thanks 0 Thanked 0 Times in 0 Posts And then it will alert the user of their star sign****** Reply With Quote 01-18-2015, 05:47 PM #3 Philip M View Profile View Forum Posts Supreme Master coder! Join Date Jun 2002 Location London, England Posts 18,371 Thanks 204 Thanked 2,573 Times in 2,551 Posts If you have been using Javascript for a while now, you should be aware that prompts and alerts are long obsolete, and I would advise that you should not be wasting your time learning this stuff. Use DOM methods to obtain input from and display messages to your users. Be aware that a value starting with 0 is a string, not a number, and so must be in quotes - that is why your code does not work. In any case you need rigorous checking to ensure that the birthday entered in this form is valid, e.g. not 56th Febtember or "Mickey Mouse". You would do best to obtain the input from select lists for month and day, expressed as numbers. A tiny bit more sophistication would allow the user to select a month by name, where the text of the option is the month name, and the value of that option the month number. Code: <select id = "monthlist" onchange = "getSignFunction()"> <option value = "0"> Choose your birth month</option> <option value = 1>January</option> <option value = 2>February</option> ... and so on </select> Then you want something like this:- Code: function getSignFunction()"{ var sign = ""; var month = document.getElementById("monthlist").value; var date = document.getElementById("datelist").value; if (month == 0) {return} // invalid choice if (month == 1 && date >=20 || month == 2 && date <=18) {sign = "Aquarius";} if (month == 2 && date >=19 || month == 3 && date <=20) {sign = "Pisces";} if (month == 3 && date >=21 || month == 4 && date <=19) {sign = "Aries";} if (month == 4 && date >=20 || month == 5 && date <=20) {sign = "Taurus";} if (month == 5 && date >=21 || month == 6 && date <=21) {sign = "Gemini";} if (month == 6 && date >=22 || month == 7 && date <=22) {sign = "Cancer";} if (month == 7 && date >=23 || month == 8 && date <=22) {sign = "Leo";} if (month == 8 && date >=23 || month == 9 && date <=22) {sign = "Virgo";} if (month == 9 && date >=23 || month == 10 && date <=22) {sign = "Libra";} if (month == 10 && date >=23 || month == 11 && date <=21) {sign = "Scorpio";} if (month == 11 && date >=22 || month == 12 && date <=21) {sign = "Sagittarius";} if (month == 12 && date >=22 || month == 1 && date <=19) {sign = "Capricorn";} alert (sign); // alert used here just for testing purposes. Crate as <span> and then use document.getElementById("spanid").innerHTML = sign to display the result to the user. } All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit. Hi I need help to finish this code with using nested if statements A price of a ticket to a passenger will be: First Class 500 Economy Class (with meal) 400 Economy Class (without meal) 200 How I can write a JavaScript code according to the following specifications: a. Read the class that the passenger wants to travel on. b. If the class is the first class, print the price of ticket. c. If the class is the economy class, ask the user if he/she wants a meal on the flight. Then print the price of the ticket according to the response of the passenger. The program should simply accept one possible strings the user enters; it is not required to work for all possible inputs such as First, first, FIRST or Yes , yes, YES. This is the code which I have been trying { var inputNum = prompt("Enter the class you want\n first class?\neconomy? :"); if (isNaN(inputNum)) { if (inputNum.match(/first class/)) { document.write("<h1><center>your Ticket is 500<\center><\h1>"); } else { prompt("<h1>if you want a meal on the flight press OK <\h1>"); document.write("<h1>your ticket is 400<h1>,"); } } Hi, I am trying to detect a users browsers and output a different code based on browser. I found this code online that uses the object detection method and it works. When I document.write(BrowserDetect.browser) it outputs Chrome, (which is what I am using). The code can be found he http://www.quirksmode.org/js/detect.html So I can't understand why the following code does not work? It ouputs the "not" in the else statement. I believe that BrowserDetect is an object and the .browser at the end is a property of the object. Can one not make an object a variable? or make an object a string? oh and BTW there is a bunch of javascript that creates the browserdetect object that can be found on the site above, but I thought it would be too unwieldy to post here. Thanks. The following script outputs: Chrome Not Working <script type="text/javascript"> document.write(BrowserDetect.browser); var browser="BrowserDetect.browser"; if(browser=="Chrome") { document.write(" Working"); } else { document.write(" Not working"); } </script> edit:: got it to work setting inBooth to false in the function where I clear the menu, but then it's refreshing to div so often while you're standing in the booth (30 frames/sec, it's a game) that nothing happens when you click the buttons to buy/sell unless you click really really fast.... anyone know a good way to check whether something is true, then toggle an innerHTML div, then once the value becomes false, toggle the innerHTML div to empty....??simply?? But if I reverse the order the opposite works but then the other doesn't...... Code: if (condition==true ) { generateSale(); inBooth=true; smithShop(); } else {inBooth=false;clearSale();} //IS PLAYER IN VENDOR BOOTH? if (condition2==true ) { generateSale(); inBooth=true; vendorShop(); } else {inBooth=false;clearSale();} Only the "generateSale()" from the second one executes. If I switch the if blocks, the second one with "generateSale()" executes. If I change "clearSale();" to a "setTimeout=('clearSale()',1000)" then both execute "generateSale()" but the div it affects flickers repeatedly as it's cleared/remade. generateSale() changes the innerHTML of a div, clearSale() just overwrites the innerHTML with ' ' Code: var sales2; function clearSale() { sales2=document.getElementById('sales2'); sales2.innerHTML=''; } function generateSale(){ sales2=document.getElementById('sales2'); sales2.innerHTML= 'Buy/Sell: '+' Gold coins: '+playerInventory[lootArray[7]]+'<br>' +' Consumables:<br>' +'You have: '+playerItems[itemArray[4]] +' arrows<br>' +'<input type="button" value="Buy" onclick="buyIt(0);">'+'10 for 50gp<br>' +'<input type="button" value="Sell" onclick="sellIt(0);">'+'10 for 25gp<br>' } Any ideas? Basically when my character enters the range of an image of a building I have a menu pop up saying you're in a vendor booth. I want it to run generateSale() which changes a div on the screen to list a bunch of stuff you can buy/sell. When your character is no longer standing in range, I want it to clear that information, so you have to be standing within range in order to trade items. Currently I can make it generates the sale menu, but it doesn't clear it when you leave the range. I've tried all kinds of "toggle" variables to set whether you're in range or not, but only the second block fires, not the first and I cannot figure out why... Any ideas? The code all works fine it just won't clear for all the different buildings, only one.... Code: <html> <script> // Author: L Freeman // Date: 11/10/10 // Purpose: Calculate student discount/vat reductions var price = 0; var vat = 17.5; var discount = 10; var reduction = 0; var deduction = 0; var reductionVAT = 0; var priceDiscount = 0; var priceNoVATDiscount = 0; // Calculate new price price = prompt("Enter price:"); // Calculate reduction reduction = (price/100) * discount; priceDiscount = (reductionVAT-reduction); priceNoVATDiscount = (price - reduction); // Calculate vat deduction deduction = (price/100) * vat; reductionVAT = (price - deduction); // Is VAT and/or a discount required? var answer = confirm ("VAT required?") if (answer) { alert ("Price = " + price + ", VAT = " + deduction + ", New Price is: " + reductionVAT) var answer = confirm ("Discount Required?") if (answer) { alert ("Price = " + reductionVAT + ", Discount = " + reduction + "New price is: " + priceDiscount) else alert ("No Discount Required. Price is: " + reductionVAT) } else alert ("No VAT required.") var answer = confirm ("Discount Required?") { if (answer) alert ("Price = " + price + ", Discount = " + reduction + "New price is: " + priceNoVATDiscount) else alert ("No Discount Required. Price is: " + price) } } </script> </html> I am having trouble getting this to work properly. What I am trying to do is come up with a simple vat deduction + student discount calculator. I cannot seem to get it working. 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? |