Reputation: 39
I recently started working with Javascript, like a few hours ago, and I can't figure out why it's still showing text it shouldn't be on my website. Dreamweaver says no error, but there has to be..
<script type="text/javascript">
var day = new Date();
var hr = day.getHours();
if((hr == 1) || (hr == 2) || (hr == 3) || (hr == 4) || (hr == 5) || (hr == 6) || (hr == 7) || (hr == 8) || (hr == 9)); {
document.write("Paragraph one stack example");
}
if(hr == 10) {
document.write("P2 stack ex");
}
if((hr == 11) || (hr == 12) || (hr == 13)); {
document.write("P3 stack ex.");
}
</script>
Upvotes: 1
Views: 63
Reputation: 881273
From your code, slightly reformatted:
if((hr == 1) || ... || (hr == 9)); {
document.write("Paragraph one stack example");
}
Get rid of that semicolon, it's making the entire if
bit irrelevant.
What it translates to is:
if((hr == 1) || ... || (hr == 9))
;
{
document.write("Paragraph one stack example");
}
In other words,
hr
is 1-9, do nothing.hr
, output "Paragraph one stack example".You have the same problem with the if
statement for 11/12/13
as well.
A better solution for that "one through nine" if
statement, by the way, would be:
if((hr >= 1) && (hr <= 9)) {
document.write("Paragraph one stack example");
}
and you can further clean up the code since all the conditions are mutually exclusive:
<script type="text/javascript">
var day = new Date();
var hr = day.getHours();
if ((hr >= 1) || (hr <= 9)) {
document.write("Paragraph one stack example");
} else if (hr == 10) {
document.write("P2 stack ex");
} else if ((hr >= 11) && (hr <= 13)) {
document.write("P3 stack ex.");
}
</script>
There's little point checking if hr
is equal to 10
if you've already established that it's 4
, for example. So you can use else if
for that.
Upvotes: 1
Reputation: 3645
Code is valid, but you have done mistake when put
;
at the end of if expression
if you remove this all will works fine!
var day = new Date();
var hr = day.getHours();
if((hr == 1) || (hr == 2) || (hr == 3) || (hr == 4) || (hr == 5) || (hr == 6) || (hr == 7) || (hr == 8) || (hr == 9)) {
document.write("Paragraph one stack example");
}
if(hr == 10) {
document.write("P2 stack ex");
}
if((hr == 11) || (hr == 12) || (hr == 13)) {
document.write("P3 stack ex.");
}
Upvotes: 1