To enable or disable an HTML input element dynamically in jQuery, set its disabled boolean property using .prop("disabled", true) to disable it and .prop("disabled", false) to enable it. Updating the DOM disabled property immediately changes form submission behavior, blocks user interaction, and triggers :disabled / :enabled CSS pseudo-classes.
1. Disabling and Enabling Inputs with .prop("disabled", ...)
Pass a boolean (true or false) directly to .prop("disabled", ...) rather than toggling attributes or strings:
<input type="text" id="promo-code" placeholder="Enter promo code" />
<button type="button" id="toggle-promo">Disable Input</button>
<script>
const $promoInput = $("#promo-code");
const $toggleBtn = $("#toggle-promo");
// Disable the input
$promoInput.prop("disabled", true);
// Re-enable the input
$promoInput.prop("disabled", false);
// Toggle based on a boolean condition (e.g., checkbox or state)
$toggleBtn.on("click", function () {
const shouldDisable = !$promoInput.prop("disabled");
$promoInput.prop("disabled", shouldDisable);
$(this).text(shouldDisable ? "Enable Input" : "Disable Input");
});
</script>
2. Toggling Groups of Inputs and Styling Disabled States
You can apply .prop("disabled", ...) across multiple matched elements at once—such as an entire fieldset or a set of form controls—and style them cleanly with CSS pseudo-classes:
// Disable or enable all inputs/buttons inside a form section
function setSectionDisabled($container, isDisabled) {
$container.find("input, select, textarea, button").prop("disabled", isDisabled);
}
setSectionDisabled($("#shipping-fields"), true);
/* CSS pseudo-class styling */
input:disabled {
opacity: 0.6;
cursor: not-allowed;
}
3. Common Traps to Avoid
- Using
.attr("disabled", "disabled")and.removeAttr("disabled"): HTML attributes represent initial markup state, whereas.prop("disabled", true/false)updates the live DOM boolean property cleanly with a single toggle call. - Assuming disabled inputs are submitted with
<form>: Native HTML forms omitdisabledcontrols from form submission payloads—if a value still needs to be sent to the server, keep it enabled or store it in a hidden field or JS request payload. - Forgetting
readonlyvs.disabled: Adisabledinput cannot be focused, edited, or submitted with a form; use.prop("readonly", true)instead if you want users to select/copy text or include the value in form submission while preventing edits.
TL;DR: Use $(selector).prop("disabled", true) to disable an input and $(selector).prop("disabled", false) to re-enable it, prefer .prop() over .attr(), and use readonly instead of disabled when the value still needs to be copied or submitted.
Are you disabling a single control based on form state, toggling a group of inputs together, or deciding between disabled and readonly?
