The correct way to work with HTML5 checkbox

HTML5 checkboxes allow users to select multiple options from a list. The correct syntax uses the input element with type="checkbox".

Syntax

<input type="checkbox" name="fieldName" value="fieldValue">

Basic Example

Here's a simple checkbox form with labels:

<!DOCTYPE html>
<html>
   <head>
      <title>HTML5 Checkbox Example</title>
   </head>
   <body>
      <form>
         <label>
            <input type="checkbox" name="maths" value="on"> Mathematics
         </label><br>
         <label>
            <input type="checkbox" name="physics" value="on"> Physics
         </label><br>
         <label>
            <input type="checkbox" name="chemistry" value="on"> Chemistry
         </label>
      </form>
   </body>
</html>

JavaScript Interaction

You can check or uncheck checkboxes programmatically and handle events:

<!DOCTYPE html>
<html>
   <head>
      <title>Checkbox with JavaScript</title>
   </head>
   <body>
      <form>
         <label>
            <input type="checkbox" id="math" name="subjects" value="mathematics"> Mathematics
         </label><br>
         <label>
            <input type="checkbox" id="science" name="subjects" value="science"> Science
         </label><br>
         <button type="button" onclick="checkSelected()">Show Selected</button>
      </form>
      
      <div id="result"></div>
      
      <script>
         function checkSelected() {
            const checkboxes = document.querySelectorAll('input[name="subjects"]:checked');
            const values = Array.from(checkboxes).map(cb => cb.value);
            document.getElementById('result').innerHTML = 'Selected: ' + values.join(', ');
         }
      </script>
   </body>
</html>

Key Attributes

Attribute Description Example
name Groups related checkboxes name="subjects"
value Value sent when form submits value="mathematics"
checked Pre-selects the checkbox checked
disabled Prevents user interaction disabled

Best Practices

Always wrap checkboxes in <label> elements for better accessibility. Use meaningful name and value attributes for form processing.

Conclusion

HTML5 checkboxes provide an intuitive way for users to make multiple selections. Proper labeling and JavaScript integration enhance user experience and form functionality.

Updated on: 2026-03-15T23:18:59+05:30

254 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements