YouTip LogoYouTip

Att Input Checked

# HTML `checked` Attribute The `checked` attribute is a boolean attribute used to specify that an `` element should be pre-selected (checked) when the page loads. This attribute is exclusively applicable to two input types: * **Checkbox** (``) * **Radio Button** (``) --- ## Browser Support The `checked` attribute is universally supported by all modern web browsers, including: * Google Chrome * Mozilla Firefox * Microsoft Edge / Internet Explorer * Safari * Opera --- ## Syntax and Usage ### HTML5 Syntax In HTML5, boolean attributes can be written in a minimized form. You only need to include the attribute name itself: ```html ``` ### XHTML Syntax In XHTML, attribute minimization is strictly forbidden. The attribute must be defined with its value explicitly declared: ```html ``` --- ## Code Examples ### Example 1: Pre-selected Checkboxes In this example, the "I have a car" checkbox is checked by default when the page loads. ```html

Select your vehicles:

I have a bike
I have a car
I have a boat
``` ### Example 2: Pre-selected Radio Buttons For radio button groups, only one option in the group should have the `checked` attribute. ```html

Please select your preferred contact method:

Email
Phone
Postal Mail
``` --- ## Dynamic Manipulation with JavaScript While the HTML `checked` attribute sets the initial state on page load, you can dynamically read or modify the checked state of an input element using JavaScript. ### Reading the Checked State To check if an element is currently selected: ```javascript const checkbox = document.querySelector('input'); if (checkbox.checked) { console.log("The checkbox is checked!"); } else { console.log("The checkbox is not checked."); } ``` ### Modifying the Checked State To programmatically check or uncheck an element: ```javascript const radioButton = document.querySelector('input'); // Check the radio button radioButton.checked = true; // Uncheck the radio button radioButton.checked = false; ``` --- ## Key Considerations 1. **Default Value vs. Current State**: The HTML `checked` attribute defines the *default* state of the input. If a user interacts with the form and changes the selection, the DOM property `element.checked` changes dynamically, but the HTML attribute in the markup remains unchanged unless modified via `element.setAttribute()`. 2. **Radio Button Groups**: If multiple radio buttons in the same group (sharing the same `name` attribute) are marked as `checked`, only the last one processed by the browser will remain selected on page load. 3. **Form Resets**: When a `
` is reset using a `` button or the `form.reset()` JavaScript method, the checkboxes and radio buttons will revert back to the state defined by the initial HTML `checked` attribute.
← Att Input DisabledAtt Input Autofocus β†’