Checkboxes and form validation

This video tutorial explains how to implement checkboxes in an HTML form and how to use JavaScript to validate the form data by checking whether at least one option has been selected. Remember, radio buttons are used when you want the user to select only one option or answer to a question, and checkboxes are used when you wish to allow the user to select more than one option (if more than one option is available).

Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Checkboxes</title>
 <script type="text/javascript">
 
 function isChecked(){
 var India = document.getElementById('India').checked;
 var France = document.getElementById('France').checked;
 var Japan = document.getElementById('Japan').checked;
 var Sweden = document.getElementById('Sweden').checked;
 
 if(India==false && France == false && Japan==false && Sweden==false){
 alert('Please select a country!');
 return false;
 }
 else{
 return true;
 }
 }
 
 </script>
 
</head>
<body>
<form action="submission.html" method="get" onsubmit="return isChecked();">
 <p>Which countries would you like to visit most?</p>
 <input type="checkbox" name="countries" value="India" id="India"/>India <br/>
 <input type="checkbox" name="countries" value="France" id="France"/>France<br/>
 <input type="checkbox" name="countries" value="Japan" id="Japan"/>Japan<br/>
 <input type="checkbox" name="countries" value="Sweden" id="Sweden"/>Sweden<br/>
 <input type="submit" value="Submit"/>
</form>
 
</body>
</html>

Next tutorial: Alert boxes and confirmation boxes