Reputation: 507
tried couple of things and was not successful. What am I missing here? I just want to do a simple alert or log, and I am not able to. Here is what I have:
function toggleEmail() {
var isChecked = document.getElementById("subscribe");
if (isChecked.checked) {
console.log('Yep, my function is being called');
}
}
toggleEmail();
<title>JavaScript Challenges</title>
</head>
<body>
<form action="">
<fieldset>
<legend>Email subscriptions</legend>
<p id="subscribe">
<label>
<input type="checkbox" name="subscribe" id="subscribe" onclick="toggleEmail()" />
Yes! I would like to receive all of your free candy!
</label>
</p>
<p id="emailpara">
<label>
Upvotes: 0
Views: 824
Reputation:
In JSFiddle, HTML on the left top side, is already the <body>
section. Your function is working. The only thing, you have to change is on the left side No wrap - in <head>
. That means that JavaScript is running in the <head>
.
<head>
<script>JavaScript</script>
</head>
<body>
HTML
</body>
Or No wrap - in <body>
is also working. That means that JavaScript is running after HTML in the <body>
section.
<head>
<head>
<body>
HTML
<script>JavaScript</script>
<body>
Upvotes: 1
Reputation: 4453
The problem with the fiddle you gave in your comment ( http://jsfiddle.net/Lucky500/j0vfzrwy/28/ ) is that the toggleEmail
function is being created in the onLoad
event handler for the page and is part of that scope, instead of being part of the global scope.
When you use direct binding in the HTML markup like this:
<input type="checkbox" name="subscribe" id="subscribe" onclick="toggleEmail()" />
Then your function must be in the global scope.
If you just change your fiddle to use "No wrap - in <head>
" it works because the function is created in the global scope. Like this: http://jsfiddle.net/j0vfzrwy/32/.
Upvotes: 1
Reputation: 4750
Try by changing this line:
<input type="checkbox" name="subscribe" id="subscribe" onclick="toggleEmail()" />
To
<input type="checkbox" name="subscribe" id="subscribe" onchange="toggleEmail()" />
Upvotes: 0