October 2nd, 2012, 05:08 AM
-
New/learning javascript, hoping for clarification for this short piece of code please
Hello all,
Im new to Javascript so i'm trying to learn from the beginning. i wrote this, as a first attempt, but no joy. can anyone help point me in the right direction/ guide me on what im doing wrong please.
Code:
<head>
<title>Untitled Page</title>
<script type="text/javascript">
function myfunction() {
var d = new date();
var day = d.getDate();
if (day == 2) {
alert("Tuesday")
}
else {
alert("some other day")
}
}
</script>
</head>
<body>
<button type="button" onclick="myfunction()"> click me</button>
</body>
</html>
Your help as always is greatly appreciated.
Kind regards
MG
October 2nd, 2012, 05:24 AM
-
"getDate" returns the day of the month, i.e. 1 to 31. "getDay" will return 0 to 6 for the day of the week.
October 2nd, 2012, 05:56 AM
-
Hi, thanks for the reply.
I changed it to 'getDay', but that doesnt work either
Code:
function myfunction() {
var d = new date();
var day = d.getDay();
if (day == 2)
{
alert("Tuesday")
}
else
{
alert("some other day")
}
}
regards
MG
October 2nd, 2012, 06:18 AM
-
What if you wrote
var d = new Date();
with capital D?
October 2nd, 2012, 06:23 AM
-
Hi, thanks for the post.
So i changed it slightly and now its kind of working. the new code looks like this:
Code:
var d = new date();
var day = d.getDay();
function myfunction() {
if (day == 2)
{
alert("Tuesday");
}
else
{
alert("some other day");
}
}
As you can see the variables are now outside the function, but i thought that shouldnt matter? you can put variable in functions right?
but now it displays "some other day" ? isnt tuesday the number 2 from 0-6 using the getDay() method??
Kind regards
MG
Last edited by mind_grapes; October 2nd, 2012 at 06:26 AM.
October 2nd, 2012, 06:39 AM
-
Yes, you can, and, maybe should, define variables inside functions!
I've tried your code in my browser, and replaced
new date();
with
new Date();
It complained "date is not defined"; changed it to Date - happy browser.
best
jwer
October 2nd, 2012, 07:35 AM
-
Hello, cheers for reply.
I changed it like yourself, and now it works. I think it may have been due to it not being a capital 'D'. Caps hey!? :-).
thank you all for your help. You've been a real help as always.
Regards
MG