0

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>

1
  • You've a scope issue, your correctly initialized fiddle works fine. (Not "onLoad", "No wrap - in <head>" instead.) Commented Aug 25, 2015 at 18:56

3 Answers 3

1

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>

Example

Sign up to request clarification or add additional context in comments.

Comments

1

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/.

Comments

0

Try by changing this line:

<input type="checkbox" name="subscribe" id="subscribe" onclick="toggleEmail()" />

To

<input type="checkbox" name="subscribe" id="subscribe" onchange="toggleEmail()" />

2 Comments

Hey Guys, I did changed to onchange, but I keep getting the error that toogleEmail is not defined.
Where have you add the javascript in your html? If you have written you js in an external file then you have to link it in html. Beside put your script link at the end of the body of your html. It should work properly. Best of luck.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.