JavaScript - My If Statement Will Not Work??!!
Similar TutorialsSo when I enter in numbers for the calculator the numerical grade shows, but not the letter grade. I dont know if I called the function wrong or if my if statement is wrong. I have no idea. Can someone help me please? Code: <!DOCTYPE html> <html lang="en"> <head> <title>Lab</title> <meta charset="utf-8"> <script> function calculateGrade () { var test1 = document.getElementById("t1") var test2 = document.getElementById("t2") var finalexam = document.getElementById("t3") var labs = document.getElementById("t4") var projects = document.getElementById("t5") var quizzes = document.getElementById("t6") var grade= document.getElementById("fng") grade.value=parseFloat(0.15*test1.value)+parseFloat(0.15*test2.value)+parseFloat(0.20*finalexam.value)+parseFloat(0.30*labs.value)+ parseFloat(0.05*projects.value)+parseFloat(0.15*quizzes.value) } function getLetterGrade() { if (totalGrade >= 90) letterGrade = "A"; else if (totalGrade < 90 && totalGrade >= 80) letterGrade = "B"; else if (totalGrade < 80 && totalGrade >= 70) letterGrade = "C"; else if (totalGrade < 70 && totalGrade >= 60) letterGrade = "D"; else if (totalGrade < 60 && totalGrade >= 50) letterGrade = "F"; } </script> </head> <body> <form id="form1" name="form1"> <table> <tr> <th colspan="2"> Score </th> </tr> <tr> <td> Test 1 </td> <td><input type="text" name="t1" id="t1" value= ""></td> </tr> <tr> <td> Test 2 </td> <td><input type="text" name="t2" id="t2" value= ""></td> </tr> <tr> <td> Final Exam </td> <td><input type="text" name="t3" id="t3" value=""></td> </tr> <tr> <td> Labs </td> <td><input type="text" name="t4" id="t4" value=""></td> </tr> <tr> <td> Projects </td> <td><input type="text" name="t5" id="t5" value=""></td> </tr> <tr> <td> Quizzes </td> <td><input type="text" name="t6" id="t6" value=""></td> </tr> <tr> <th colspan="2"> <input type="button" name="b1" id="b1" value="Calculate Grade" onclick="calculateGrade(); getLetterGrade()"> </th> </tr> <tr> <td> Final numerical grade </td> <td><input type="text" name="fng" id="fng" style="border: none"></td> </tr> <tr> <td> Final letter grade </td> <td><input type="text" name="letterGrade" id="letterGrade" style="border: none"></td> </tr> </table> </form> </body> </html> I have a page with a Geo IP redirect that's supposed to redirect users from London to URL#1 and the rest to URL#2. It's an external geo ip lookup service. First comes the IP lookup: Code: <script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"> /* GeoIP Deny Access by City and Redirect Javascript 1.0 http://wiki.category5.tv/MaxMind_GeoIP_API API (c) MaxMind - www.maxmind.com - used with permission "GeoIP Deny Access by City" script by Robbie Ferguson, www.Category5.TV You are free to use and share this script, however this notice must remain intact. */ </script> And then, and here's the problem I think, is the redirects inside an if/else: Code: <script type="text/javascript"> var city=new Array("London, H9") var redirect="http://www.URL1.com" var redirect2="http://www.URL2.com" /* do not edit past this line */ Array.prototype.inArray = function(q) { for(i in this) { if(this[i].toUpperCase() === q) return true; } } var myCity=geoip_city().toUpperCase() var myRegion=geoip_region().toUpperCase() if(city.inArray(myCity+", "+myRegion)) { window.location = redirect; } else { window.location = redirect2; } The redirect works if you are indeed from London. So if the if-statement is true, "window.location = redirect" works, but if the statement is not true, "window.location = redirect2" doesn't seem to be called. Help would be extremely appreciated Ive searched on this board but cant find out why this doesn't work. Code: <script type="text/javascript"> function showSelected(val) if (val == "Nil") { document.getElementById('JustText').innerHTML='hi' } else { document.getElementById('selectedResult').innerHTML="<a href='mailto:" + val + "'>" + val + "</a><p>" } </script> Hey everyone, I'm a newbie writing a tic tac toe program using OOP. It was simple setting it up so that a player could click on a box to put an X or an O there, but I've run into serious issues when trying to make it so a player couldn't overwrite the AI's choice and the AI couldn't overwrite the player's. An example of this would be if I made the top right box an X and the AI then made the center box an O, and then I accidentally clicked the center box and made it into an X. I want to prevent that. Every box on the grid is an object with the property of "taken" that helps the program know if a box is empty or not, so as to avert any overwriting in the first place. If the box is empty, this.taken = 0. If the box is filled by a player, taken = 1. If filled by AI, taken = 2. I made it matter whether it was AI or human so later i can check if one of them got tic tac toe. Anyway, by default the constructor class sets this.taken = 0. But the method for checking availability and writing the X or O uses a switch which checks if taken = 0. If it is, it sets taken to either 1 or 2 and writes the necessary symbol. If taken = 1 or 2, it just alerts the player that the spot is taken. But for some reason the switch statement can't tell when taken = anything other than 0. It always executes the code for 0 even though the code for 0 inherently makes it so that taken never equals 0 again, which means case 0 cannot happen anymore. Below is the code with notes. Code: function main(input){//start of main function// function Click(who, where, what){ //this is the method for checking if it's taken or not and writing the X or O if it isn't// /*the argument who represents a number. 0 is no one, 1 is human, 2 is AI; where is a string literal representing the spot on the grid*/ switch(this.taken){ case 0: this.taken = who; document.getElementById(where).innerHTML = what; break; case 1: alert("this spot is taken"); break; case 2: alert("this spot is taken"); }//end switch }//end Click function Box(inputhere){//start of class// this.taken = 0; this.pick = Click; } //end of Box class// //object declarations (I cut out most of them and left only the relevant ones// var topleft = new Box(); var topmid = new Box(); var topright = new Box(); var centerright = new Box(); //end of object declarations// switch (input){ /*in each .pick(), the first arg is whether or not a player chose it (1 = player did, 2 = comp did). The second arg is which box and the third is whether to put an X or O. The input variable in the switch statement is an argument passed through main() when the player clicks on a box. Topleft passes 1.1, topmid passes 1.2 and so on.*/ case 1.1:{ //The first instance of .pick() in each case is what the player did. The second is what the AI will do in repsonse.// topleft.pick(1, "topleft", "X"); topmid.pick(2, "topmid", "<span>O</span>"); break; }//end of case 1.1 case 1.3:{ topright.pick(1, "topright", "X"); centerright.pick(2, "centerright", "<span>O</span>"); break; }//end of case 1.3 }//end of switch }//end of main// Is there anyone who has any idea why on earth this is happening? I've been at it for an embarrassing amount of hours. Also, thanks to anyone who even considers helping : ) (feel free to flame me if my code sucks or my post is too long or anything). Hello everyone, I am using javascript and I have a radio button that the user selects and I have a function to see which button was selected, but i'm trying to use the return of that if statement in another statement. Basically another part of the function is dependent on what the user selects in the radio button. Here is what I have so far (I have some things in there that might not work because i'm trying to figure out what works): Code: <script type="text/javascript"> function getSelectedRadio() { len = document.dates.dep.length // returns the array number of the selected radio button or -1 if no button is selected if (document.dates.dep[0]) { // if the button group is an array (one button is not an array) for (var i=0; i<len; i++) { if (document.dates.dep[i].checked) { return i } } } else { if (document.dates.dep.checked) { return 0; } // if the one button is checked, return zero } // if we get to this point, no radio button is selected return -1; } function Calculate() { var i = getSelectedRadio(); if (i == -1) { alert("Please select if Marine entered Delayed Entry Program"); } else { if (document.dates.dep[i]) { return document.dates.dep[i].value; } else { return document.dates.dep.value; } } if (document.dates.yearDEAF.value < 1985 && document.dates.monthDEAF.value < 01 && document.dates.dayDEAF.value < 01 && first return from above ) { document.dates.yearDEP.value = (document.dates.yearDEAF.value); document.dates.monthDEP.value = (document.dates.monthDEAF.value); document.dates.dayDEP.value = (document.dates.dayDEAF.value); document.dates.yearPEBD.value = (document.dates.yearDEAF.value); document.dates.monthPEBD.value = (document.dates.monthDEAF.value); document.dates.dayPEBD.value = (document.dates.dayDEAF.value); } else if (document.dates.yearDEAF.value < 1985 && document.dates.monthDEAF.value < 01 && document.dates.dayDEAF.value < 01 && second return from above ) { document.dates.yearPEBD.value = (document.dates.yearAFADBD.value); document.dates.monthPEBD.value = (document.dates.monthAFADBD.value); document.dates.dayPEBD.value = (document.dates.dayAFADBD.value); document.dates.yearDEP.value = "N/A"; document.dates.monthDEP.value = "N/A"; document.dates.dayDEP.value = "N/A"; } } </script> I color coded in red the returns i'm trying to reference and where they need to be. Is this possible, and if so how can I do it? I haven't been able to find anything on the internet so far. Any help is greatly appreciated! Hello all, I made a fade script that will fade any element in or out. Works great on all browser I've tested but IE 7. With IE I have only tested this will IE 8 and IE 7. IE 7 the effect doesn't work. No error message or anything. I'm unsure what to do from here. I was hoping I could find some help here. Code: function fade(obj, duration, toggle) { steps = 1000; elem = document.getElementById(obj); function fadeIn() { for(var i = 0; i <= 1; i+=(1/steps)) { setTimeout("elem.style.opacity = "+ i +"", i * duration); setTimeout("elem.style.filter='alpha(opacity="+ i * 102 +")'", i * duration); } } function fadeOut() { for(var i = 0; i <= 1; i+=(1/steps)) { setTimeout("elem.style.opacity = "+ (1-i) +"", i * duration); setTimeout("elem.style.filter='alpha(opacity="+ (1-i) * 102 +")'", i * duration); } } /* One for Fade in and anything will be fade out*/ if(toggle == 1) { fadeIn(); } else { fadeOut(); } } Thanks, Jon W Hello, I have just started studying JS and don't know a whole lot about it. One exercise I have been given is to use the while statement to ask the user to guess a number between one and ten. this is the code I have attempted so far but it does not work. Simple for any one who is good at this. Impossible to me. Any takershttp://www.codingforums.com/images/smilies/confused.gif <!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>While Test</title> <script type="text/javascript"> <!-- function whileTest(){ var number = 4; var answer = 0; while(number != answer ){ answer=prompt("Guesss a number between 1 and ten",""); } alert("4 is the correct answer") //--> </script> </head> <body onLoad="whileTest();"> </body> </html> can someone help me with this pls: Code: function anything() { var tegenover = document.getElementById("minlas"); var septo = document.getElementById("combo_2"); //prijs verbinder per meter var serr = document.getElementById("comba_2"); //prijs verbinder per meter var seprr = document.getElementById("combb_2"); //prijs verbinder per meter var septrr = document.getElementById("combc_2"); //prijs verbinder per meter var nocho = document.getElementById("wide"); //breedte band in mm document.getElementById("totprijslas").value = Math.round(100*((parseFloat(septo.value) + parseFloat(serr.value) + parseFloat(seprr.value) + parseFloat(septrr.value)) * parseFloat(nocho.value))/1000)/100; } the value returned of totprijslas can be anything between 0 and 1000,but i want the value of "totprijslas" to be a minimum of "50",so for example if result is 30 then i need it to show 50.can someone help me with an if statement for this.thx No matter what first name and last name I enter I get "Wrong!" I get wrong if I enter john smith or bill shaw Code: <html> <head> </head> <body> <script type="text/javascript"> var input; var first; var last; input = window.prompt("Please Enter First and Last Name (e.g. Joe Smith)"); if ((first == "John" || first == "john") && (last == "Smith"|| last == "smith")){ document.write ("Welcome John Smith"); } if ((first == "Bill" || first == "bill") && (last == "Shaw"|| last == "Shaw")){ document.write ("Welcome Bill Shaw"); } else { document.write("Wrong!"); } </script> <body> </html> I am relatively new to JavaScript coding, and I a having some problems with an IF statement. I want the IF statement to tell me when the number is below the minimum. Code: function main (txtpamphletMin,txtpamphletMax,optQuality,selIncrement,txtResults) { var txtpamphletMin,txtpamphletMax,optQuality,selIncrement; var amount = 100; var errorMsg = ""; var results = ""; pamphletMin = pamphletMin.value; //Make sure that the minimum number of pamphlets required is entered if (pamphletMin == "pamphletMin<100") { errorMsg = "Number of pamphlets must be above 100"; } else { pamphletMin = txtpamphletMin.value; //get the number of pamphlets from the text box errorMsg = validatepamphletMin(Minimum Pamphlets); } I know that this is no the entire statement but I am just having problems with this one. Can anyone help? Code: <script type="text/javascript"> var clicks=0; function linkClick(){ document.getElementById('clicked').value = ++clicks; if (clicks>2) { var answer = confirm ("What choice would you like?") if (answer) window.open("choiceA.html",'','scrollbars=no,menubar=no,height=600,width=800,resizable=no,toolbar=no,location=no,status=no') else (answer) window.open("choiceB.html",'','scrollbars=no,menubar=no,height=450,width=450,resizable=no,toolbar=no,location=no,status=no') } } </script> OR Code: <script type="text/javascript"> var clicks=0; function linkClick(){ document.getElementById('clicked').value = ++clicks; if (clicks>2) { var answer = confirm ("What choice would you like?") if (answer){ window.open("choiceA.html",'','scrollbars=no,menubar=no,height=600,width=800,resizable=no,toolbar=no,location=no,status=no') } else (answer) window.open("choiceB.html",'','scrollbars=no,menubar=no,height=450,width=450,resizable=no,toolbar=no,location=no,status=no') } } </script> OK, so now I'm trying so open a specific page depending on the users answer. I am aware that my code should look like this: Code: if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true } However because of my click counter I have been unable to do this. My code itself does kinda work BUT choiceA open both choiceA and choiceB's pages :-( choiceB is fine and opens choiceB's page. I know that it's probably a small syntax error but I just can't see where. Thank-you in advance for your assistance. Hi! I am a total newbie I'm afraid but I really enjoy learning javascript. Today I'm trying to write an if statement. I want the image1 on a web page to change when it's clicked to image2. Then I want the if statement to see if the source of the image is the changed image2.jpg (or still the original image1.jpg) and if it is the changed one I want another click to change it to image3. Here's my code, but the change to image 3 is not working: /* image change start */ var imgchanger = document.getElementById("changingimage"); imgchanger.onclick = function() { imgchanger.src = "image2.jpg"; }; /* image change 2 start */ if (imgchanger.src == "image2.jpg") { imgchanger.onclick = function() { imgchanger.src = "image3.jpg"; }; } I've got this code below to change an images source url based on the clicks from a dropdown menu. Is it possible to shorten this with some sort of if/or statement instead of all the else if's? something that says "if crenate or serrate or this or that, do this" here's the function: Code: function change3(picName,choice) { var url = (document[picName].src); if (/crenate\D{1}/.test(url)) { url = url.replace(/crenate/, choice) document[picName].src=(url); } else if (/margin_finelyserrate\D{1}/.test(url)) { url = url.replace(/margin_finelyserrate/, choice) document[picName].src=(url); } else if (/margin_lobed\D{1}/.test(url)) { url = url.replace(/margin_lobed/, choice) document[picName].src=(url); } else if (/margin_undulate\D{1}/.test(url)) { url = url.replace(/margin_undulate/, choice) document[picName].src=(url); } else if (/doubleserrate\D{1}/.test(url)) { url = url.replace(/doubleserrate/, choice) document[picName].src=(url); } else if (/leaf_shapes\D{1}/.test(url)) { url = url.replace(/leaf_shapes/,"leaf_shapes/" + choice) document[picName].src=(url); } } The dropdown menu just has options written like this: Code: <li id="margin1"><a href="javascript:passit4('entire')" onMouseover="change1('pic8','image34')" onclick="ShowContent('uniquename3'); change3('pic2','entire');" onMouseout="change1('pic8','image_off');">sample link (entire)</a></li> Code: function showResults( results ) { if ( results.length == 0 ) { msg = "no projects found"; } else {msg = results [0]; } document.getElementById("RESULTS").innerHTML = msg; //= results.join( "<br/>" ); cannot get it to show "no projects found" for 0 results and also to show all multiple results if multiple are found. works right now for 1 result but not multiple. the =results.join( "<br/>" ); works if multiple but then it will not say no projects found for 0 results. I'm not very familiar with java script at all, but could someone please explain how to make an if else else statement that follows these guidelines? 1. If the income is $70,000 or above the tax rate starts at 70% (the % sign will not show) 2. If the income is $20,000 or below the tax rate starts at 10% (the % sign will not show) 3. Otherwise the tax rate starts at 25% Thank you SO much! Hello CF im wondering how could i use an if statement to have something pop up when visitors visit my site that allows them two choices. it would say something like this. Would you Like to always see the navigation Bar? then they have two options. Yes and No. then depending on what they choose it will either have the code use the absolute or the fixed positioning attribute for the whole code. Or is this just not possible? If you want me to explain it more just ask. I want to know how I can update my power_points field if a select option is chosen. For example: if animal guardian is chosen Power_points - (attribute_level * 1) if combined attacks is chosen power_points - (attribute_level * 1) if elemental control is chosen power_points - (attribute_level * 3) etc... Here is my current script: Code: <?php session_start(); ?> <form> <table cellpadding="3" cellspacing="3"> <tr> <th>Attribute</th> <th>Level</th> <th>Power Points:</th> <th>Character Points:</th> </tr> <tr> <td><input type="text" readonly="readonly" value="Scout/Knight Powers" size="19" name="attribute1" /></td> <td><select name="level" onclick="power(), remain()"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> </select></td> <td align="center"><input type="text" name="power_points" id="power_points" size="1" readonly="readonly"/></td> <td align="center"><input type="text" name="cp_remain" id="cp_remain" size="1" readonly="readonly" /></td> </tr> </table> </form> <form method="POST" action="test_batosai.php"> <table><tr><td> <div id="dynamicInput1"> <table cellpadding="3" cellspacing="3"> <thead> <tr> <th>Sub-Attribute</th> <th>Level</th> <th>Notes <i>(optional)</i></th> </tr> </thead> <tbody> <tr> <td> <select name="attribute[]" size="1"> <option value="1">Animal Guardian</option> <option value="2">Combined Attacks</option> <option value="3">Elemental Control</option> <option value="4">Emotional Control</option> <option value="5">Item Of Power</option> <option value="6">Knight Attack</option> <option value="7">Rejuvenation</option> <option value="8">Sailor Scout Attack</option> </select></td> <td> <select name="attribute_level[]"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> </select></td> <td><textarea name="sub_notes[]" rows="1" cols="30"> </textarea></td> </tr> </tbody> </table> </div> <div id="cloneDiv1"> </div> </td> <td> <div id="dynamicInput2"> <table cellpadding="3" cellspacing="3"> <thead> <tr> <th>Neutral Attribute</th> <th>Level</th> <th>Notes <i>(optional)</i></th> </tr> </thead> <tbody> <tr> <td> <select name="attribute2[]" size="1"> <option value="1">Acrobatics</option> <option value="2">Appearance</option> <option value="3">Art Of Distraction</option> <option value="4">Combat Mastery</option> <option value="5">Damn Healthy!</option> <option value="6">Divine Relationship</option> <option value="7">Energy Bonus</option> <option value="8">Extra Attacks</option> <option value="9">Focused Combat</option> <option value="10">Fortified Body</option> <option value="11">Heightened Negaverse Power</option> <option value="12">Heightened Senses</option> <option value="13">Heightened Scout Powers</option> <option value="14">Massive Damage</option> <option value="15">Powerful Mind</option> <option value="16">Special Attack/Defense</option> <option value="17">Speed</option> <option value="18">Strong Soul</option> <option value="19">Supernatural Training</option> <option value="20">Unique Character Attribute</option> </select></td> <td> <select name="attribute_level2[]"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> </select></td> <td><textarea name="neutral_notes[]" rows="1" cols="30"> </textarea></td> </tr> </tbody> </table> </div> <div id="cloneDiv2"> </div> </td></tr></table> <input type="button" value="Add another Sub-Attribute" onClick="addInput('dynamicInput1','cloneDiv1');"> <input type="button" value="Add another Neutral Attribute" onClick="addInput('dynamicInput2','cloneDiv2');"> <input type="submit" /><input type="reset" /> </form> <script type="text/javascript"> var counter = 1; var limit = 10000000;// Set a limit if you want to function addInput(divFrom,divTo){ if (counter == limit) { alert("You have reached the limit of adding " + counter + " inputs"); } else { var newdiv = document.createElement('div'); newdiv.innerHTML = document.getElementById(divFrom).innerHTML; document.getElementById(divTo).appendChild(newdiv); counter++; } } //function for Power Points function power() { var first,res1; //Take the value of first textbox and convert it to float first=parseFloat(document.forms[0].level.value); res1=(first)*10; //show the result in the result textbox document.forms[0].power_points.value=res1; } //end function for Power Points //function for Character Points remaining function remain() { var first,res2; //Take the value of first textbox and convert it to float first=parseFloat(document.forms[0].level.value); res2=10-((first)*4); //show the result in the result textbox document.forms[0].cp_remain.value=res2; } //end function for Character Points </script> Can anyone help? 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> Hello CodingForums. Im having problems making my hidden divs close and open how I want them to. I have one hidden div which opens and reveals and login area. but near the submit button I have a signup button and I want the login div to close and the sign up one to open but I can't get the login one to close. I'm sure you experts could fix this easily for me. Javascript: Code: <script language="javascript"> function toggle() { var ele = document.getElementById("loginbox"); var text = document.getElementById("displayText"); if(ele.style.display == "block") { ele.style.display = "none"; text.innerHTML = "show"; } else { ele.style.display = "block"; text.innerHTML = "hide"; } } function signup() { var ele = document.getElementById("signup"); var login = document.getElementById("loginbox"); var text = document.getElementById("displayText"); if(ele.style.display == "block") { ele.style.display = "none"; text.innerHTML = "show"; if(login.style.display == "block") { login.style.display = "none"; text.innerHTML = "hide"; } else { } } else { ele.style.display = "block"; text.innerHTML = "hide"; } } </script> Html: Code: <div id="signup" style="display: none"> <p> test </p> </div> <div id="loginbox" style="display: none"> <form id="loginscript" action="search.php" method="post"> <p>Your Username:<input type="text" name="Username" /></p> <p>Your Password:<input type="password" name="Passwrod" /></p> <input type="submit" class="hiddenbutton" value="login" /> <input type="reset" class="hiddenbutton" value="reset" /> <a href="javascript:signup();"><input type="button" class="hiddenbutton" value="signup" /></a> </form> </div> <a href="javascript:toggle();"><input type="submit" class="topbutton" name="login" value="Login In or Sign Up" /></a> |