Form Selectors
Special selectors for inputs, checkboxes, and their states.
Syntax
$(":checked"), $(":text"), $(":selected")jQuery has selectors made for forms, so you rarely need to write long attribute selectors.
| Selector | Selects |
|---|---|
:input | all input, textarea, select, button |
:text, :checkbox, :radio | inputs of that type |
:checked | checked checkboxes/radios |
:selected | selected option elements |
:disabled | disabled form controls |
Example
Loading editor…
Press Run to see the result.
When to use it
- A checkout form disables all :input elements during submission to prevent double-posting.
- An admin panel counts :checked checkboxes to show a "3 items selected" label in bulk-action toolbars.
- A survey script reveals extra fields only when a specific :radio button is :checked.
More examples
Disable all inputs on submit
:input matches all form controls (input, select, textarea, button), disabling them all on submit.
<form id="order">
<input type="text" name="name" />
<input type="email" name="email" />
<button type="submit">Place Order</button>
</form>
<script>
$(function () {
$("#order").on("submit", function () {
$(":input", this).prop("disabled", true);
});
});
</script>Count selected checkboxes
:checked inside .item:checked dynamically counts only the ticked checkboxes each time one changes.
<input type="checkbox" class="item" value="1" />
<input type="checkbox" class="item" value="2" />
<input type="checkbox" class="item" value="3" />
<p id="count">Selected: 0</p>
<script>
$(function () {
$(".item").on("change", function () {
var n = $(".item:checked").length;
$("#count").text("Selected: " + n);
});
});
</script>Show extra field for specific radio
Listens to radio changes and shows billing fields only when the "pro" option is selected.
<label><input type="radio" name="plan" value="pro" /> Pro</label>
<label><input type="radio" name="plan" value="free" /> Free</label>
<div id="billingFields" style="display:none">
<input type="text" placeholder="Card number" />
</div>
<script>
$(function () {
$(":radio[name=plan]").on("change", function () {
$("#billingFields").toggle($(this).val() === "pro");
});
});
</script>
Discussion