Checkboxes


Checkboxes (<input type="checkbox">)

Checkboxes are essential HTML form elements that allow users to select zero or more options from a list. They are versatile for gathering user preferences and multiple choices, enhancing user interaction on web forms.


Example 1: Basic Checkbox

<label for="newsletter">Subscribe to Newsletter:</label>
<input type="checkbox" id="newsletter" name="subscribeNewsletter" value="yes">

Explanation This example demonstrates a fundamental checkbox setup. The label enhances accessibility, making the text next to the checkbox clickable to toggle its state. The id and name attributes are crucial for form submission and JavaScript interaction.


Example 2: Pre-checked Checkbox

<label for="rememberMe">Remember me:</label>
<input type="checkbox" id="rememberMe" name="rememberUser" value="true" checked>

Explanation The checked attribute is a boolean attribute that automatically selects the checkbox upon page load. This is useful for common options or to indicate a previously saved preference.


Example 3: Disabled Checkbox

<label for="readOnlyOption">Read-only option:</label>
<input type="checkbox" id="readOnlyOption" name="readOnly" value="unavailable" disabled>

Explanation The disabled attribute renders the checkbox unusable, preventing users from checking or unchecking it. This is often used when an option is not applicable or requires specific conditions to be met.


Example 4: Checkbox Group (Multiple Selections)

<p>Choose your favorite fruits:</p>
<input type="checkbox" id="apple" name="fruit" value="apple">
<label for="apple">Apple</label><br>
<input type="checkbox" id="banana" name="fruit" value="banana">
<label for="banana">Banana</label><br>
<input type="checkbox" id="orange" name="fruit" value="orange">
<label for="orange">Orange</label>

Explanation To create a group where users can select multiple options, give all related checkboxes the same name attribute. Each input within the group should have a unique id and value.


Example 5: Checkbox with JavaScript Interaction (Basic Toggle)

<label for="toggleFeature">Enable Feature:</label>
<input type="checkbox" id="toggleFeature" name="featureToggle" value="active" onclick="alert('Feature state changed!');">

Explanation Checkboxes can be integrated with JavaScript for dynamic web experiences. The onclick event handler here triggers an alert, demonstrating a basic interaction when the checkbox's state changes.