:checked Selector
Matches all elements that are checked or selected.
.checked()
The :checked
selector works for checkboxes, radio buttons, and options of select
elements.
To retrieve only the selected options of select
elements, use the :selected
selector.
Determine how many input elements are checked.
JS
<form>
<p>
<input type="checkbox" name="newsletter" value="Hourly" checked="checked" />
<input type="checkbox" name="newsletter" value="Daily" />
<input type="checkbox" name="newsletter" value="Weekly" />
<input type="checkbox" name="newsletter" value="Monthly" checked />
<input type="checkbox" name="newsletter" value="Yearly" />
</p>
</form>
<div></div>
CSS
div {
color: red;
}
HTML
var countChecked = function () {
var n = $("input:checked").length;
$("div").text(n + (n === 1 ? " is" : " are") + " checked!");
};
countChecked();
$("input[type=checkbox]").on("click", countChecked);
DEMO
Identify the checked radio input.
JS
<form>
<div>
<input type="radio" name="fruit" value="orange" id="orange" />
<label for="orange">orange</label>
</div>
<div>
<input type="radio" name="fruit" value="apple" id="apple" />
<label for="apple">apple</label>
</div>
<div>
<input type="radio" name="fruit" value="banana" id="banana" />
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
CSS
input,
label {
line-height: 1.5em;
}
HTML
$("input").on("click", function () {
$("#log").html($("input:checked").val() + " is checked!");
});
DEMO