Home and Learn: Javascript Programming Course


The final function we need is for the checkbox. You can have 1 or more checkboxes on a form. We only have 1, so checking it is fairly straightforward. If you have more than checkbox, though, you do the testing in exactly the same way as for radio buttons.

But here's the code for the checkCheckbox function:

Javascript code to test a checkbox

The IF statement just tests the terms HTML element (a checkbox) for a value of checked. If it has been checked then we can return a value of true, as the user has agreed to the terms and conditions. If the checkbox has not been checked, the value will be "undefined" and we can return a value of false.

Test it out. Leave the check box unchecked. Click the submit button and you'll see this:

checkbox error message

When you check the box the error message should disappear.

In the final part of this HTML forms tutorial we'll finish off the validate function, so that the form can be sent.

Back to the Home Page

Email us: enquiry at homeandlearn.co.uk