Selector checked
The selector :checked
selects elements that are selected, that is, those that have the attributes checked
or selected
. The :checked
selector works with checkboxes (checkbox
) and radio buttons (radio
), as well as for elements with the option
tag. To get only the selected options of select
elements, use the selected
selector.
Syntax
This is how we select elements with the checked
attribute:
$(':checked');
Example
Let's display the number of selected checkboxes each time you select a checkbox. As you can see, before your first click, the default checkboxes will be displayed, which are the second and fourth:
<form>
<p>
<input type="checkbox" name="cbox" value="one">
<input type="checkbox" name="cbox" value="two" checked="checked">
<input type="checkbox" name="cbox" value="three">
<input type="checkbox" name="cbox" value="four" checked>
<input type="checkbox" name="cbox" value="five">
</p>
</form>
<div></div>
div {
color: green;
}
let countChecked = function() {
let n = $('input:checked').length;
$('div').text('Checked: ' + n);
};
countChecked();
$('input[type=checkbox]').on('click', countChecked);
Example
Let's display the value of each selected radio switch below on click:
<form>
<div>
<input type="radio" name="digits" value="one" id="one">
<label for="one">one</label>
</div>
<div>
<input type="radio" name="digits" value="two" id="two">
<label for="two">two</label>
</div>
<div>
<input type="radio" name="digits" value="three" id="three">
<label for="three">three</label>
</div>
<div id="text"></div>
</form>
input, label {
line-height: 1.5em;
}
$('input').on('click', function() {
$('#text').html($('input:checked').val() + ' is checked!');
});