r/javaScriptStudyGroup • u/beimy159357 • Nov 24 '17
Need help fixing a bug
This code is supposed to simply ask for a preference for am/pm or military time then display the current time. When I run it it doesn't do anything. Any help would be appreciated.
<!DOCTYPE HTML>
<html> <head> </head> <body> <script> var myClock = new clock(); var myClock.setTime(); var myClock.displayTime(); var d = new Date(); function clock(){ this.setTime = function(){ this.hours = document.getHours(); this.minutes = document.getMinutes(); this.seconds = document.getSeconds(); } this.displayTime = function(){ var a = prompt("A.M./P.M. or Military"); if(a == "ampm"){ if(this.hours>=12&&this.minutes>0&&this.seconds>0){ document.writeln("Time:" + (this.hours-12) + ":" + this.minutes + ":" + this.seconds + "p.m."); } else{ document.writeln("Time:" + this.hours +":" + this.minutes + ":" + this.seconds + "a.m."); } else{document.writeln("Time:" + this.hours + ":" + this.minutes + ":" + this.seconds + "hrs");} } } } </script> </body> </html>
1
u/[deleted] Nov 24 '17 edited Nov 24 '17
First of all, please learn markdown (or just click the little link that says "formatting help" under the comment box). Indent your code by 4 space before you post it here so it doesn't show up as a single line of text. Generally, people are going to be inclined to ignore questions containing code that isn't formatted.
Second, please learn how to use your JS console, it will tell you exactly what is wrong with your code. Let's go over it.
The first error in the console is
referring to this line:
var myClock.setTime();This is because you havevarcreating a new variablemyClockand then JS expects a semicolon or a new statement when in reality you did not mean to create a new variable at all. This is why you don't copy and paste stuff. Remove thevaron that line (and the next line) and that will fix the first errors.The next error is
This is because you have 2
elsestatements. you can have only one else and it has to be the last condition. You need to replace the firstelsewith anelse if(another condition). I assume the "other condition" you want to use is something likethis.hours < 12Next error is
The document does not have this method, the date object does. you want to replace
documentwithnew Date()on this and the next three lines (egnew Date().getHours();)At this point your code still has logic bugs but it's not throwing any errors and your prompt is showing.
Seriously though, learn how to use your favorite browser's console before you go any further. People generally don't like it when you ask them to debug your code when you have done no debugging yourself whatsoevver.