Checkboxes are a popular form control in HTML, allowing users to select one or multiple options from a list. By default, checkboxes are not checked in HTML. However, there might be cases where you want to keep a checkbox checked by default when the web page loads. In this blog post, we’ll discuss how to achieve that and even maintain the checked state after a form is submitted.
Make a Checkbox Checked by Default in HTML
To make a checkbox checked by default, you need to add the checked attribute to the <input> tag. The following example shows how to create a checked checkbox:
Here, the checkbox will be checked by default when the page loads, as we have added the checked attribute to the input tag. Note that the attribute does not require a value; simply adding checked is enough.
Maintain the Checked State After Form Submission
In some cases, you might want to maintain the checked state of a checkbox after a form is submitted. Consider a scenario where a user submits a form, and the page reloads to display validation errors. In this case, it would be convenient to maintain the state of the checkboxes, so the user doesn’t have to select them again.
To do this, you can use PHP (or any other server-side language) to check if the checkbox was selected before the form was submitted. If it was, you can dynamically add the checked attribute to the input tag. Here’s an example of how to achieve this with PHP:
$example = isset($_POST[‘example’]) ? ‘checked’ : ”;
?>
<form method=”post” action=””>
<input type=”checkbox” name=”example” value=”1″ <?php echo $example; ?>>
<input type=”submit” value=”Submit”>
</form>
In the example above, we first check if the ‘example’ checkbox was checked before the form was submitted by using the isset() function. If it was, we store the string ‘checked’ in the $example variable; otherwise, we leave it empty.
Next, we use the echo statement to output the value of the $example variable as part of the input tag. If the checkbox was checked before the form was submitted, the checked attribute will be added to the input tag, maintaining its state.
Conclusion
In this blog post, we’ve discussed how to make a checkbox checked by default in HTML and how to maintain its checked state after a form submission using PHP. Keeping a checkbox checked can be helpful in various scenarios, such as providing default selections or retaining user input after form validation. By following the examples in this post, you can easily implement this functionality in your web projects.