0

I am trying to create a simple checkbox and button that will verify that a user has read a TOS. For some reason, my code doesn't work. Page loads, but pressing the button doesn't have the desired effect. Firebug says I'm error free, so I figure I'm misunderstanding how something works. Can anyone explain what I'm doing wrong here? I'm still pretty new to Javascript.

<html>
<head>
<script language="javascript" type="text/javascript">
function validateForm()
{
    if(document.getElementById("TOSbox").checked)
    {
       window.location.href = "/give.html";
    }
    else
    {
        document.getElementById("TOSWarning").innerHTML="You need to agree to the TOS first.";
    }
}
</script>
</head>
<body>
    This is where the TOS goes.
    <br>
    <form name="TOSform" action="">
        <input type="checkbox" name="TOSbox" value="checked">I have read and agree to the Terms of Service.<br>
        <button onclick="validateForm()">I Agree</button> 
    </form>
    <p id="TOSWarning"></p>
</body>
</html>
phatskat
  • 1,797
  • 1
  • 15
  • 32
  • Make sure to prevent the default behavior of the form. – elclanrs Nov 20 '13 at 22:28
  • 2
    *"I am trying to create a simple checkbox and button that will verify that a user has read a TOS"* That's easy! The answer is: **No, they haven't**. No need to look at the checkbox at all. – T.J. Crowder Nov 20 '13 at 22:28
  • @elclanrs does the code look like OP knows how the prevent the default behaviour? – Kijewski Nov 20 '13 at 22:28
  • @Kay: Maybe not, that's what Google is for, now OP got the search term "prevent default form javascript" and boom thousands of answers. – elclanrs Nov 20 '13 at 22:31

3 Answers3

2

Your <button> needs a type="button", for starters to avoid submitting the form (or return false when the form isn't valid). Also, you're using getElementById but your checkbox has no id, only a name. Try:

<input type="checkbox" name="TOSBox" id="TOSbox" value="checked">I have read and agree to the Terms of Service.<br>
<button type="button" onclick="validateForm();">I Agree</button> 
Kijewski
  • 25,517
  • 12
  • 101
  • 143
phatskat
  • 1,797
  • 1
  • 15
  • 32
1

You need to return false to prevent the default submission behavior.

<button onclick="validateForm(); return false;">I Agree</button> 
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Related: https://stackoverflow.com/a/10079197/1026459

When a button is used without a type inside of a form, its default type is submit.

Consider using <button type="button"...> to avoid posting the form when the button is pressed.

Also, in the javascript you are using, you are looking for an id="TOSbox", but your checkbox is actually only using name="TOSbox". You should probably add the id to it

<input type="checkbox" id="TOSbox" name="TOSbox" value="checked">
Community
  • 1
  • 1
Travis J
  • 81,153
  • 41
  • 202
  • 273