To disable a button, specify the
disabled
global attribute on it, like so:
<
input
type
=
"
button
"
value
=
"
Disable me
"
disabled
/>
Setting the disabled attribute
You can enable and disable buttons at run time by setting
disabled
to
true
or
false
. In this example our button starts off enabled, but if you press it, it is disabled using
button.disabled = true
. A
setTimeout()
function is then used to reset the button back to its enabled state after two seconds.
<
input
type
=
"
button
"
value
=
"
Enabled
"
/>
const
button
=
document
.
querySelector
(
"input"
)
;
button
.
addEventListener
(
"click"
,
disableButton
)
;
function
disableButton
(
)
{
button
.
disabled
=
true
;
button
.
value
=
"Disabled"
;
setTimeout
(
(
)
=>
{
button
.
disabled
=
false
;
button
.
value
=
"Enabled"
;
}
,
2000
)
;
}
Inheriting the disabled state
If the
disabled
attribute isn't specified, the button inherits its
disabled
state from its parent element. This makes it possible to enable and disable groups of elements all at once by enclosing them in a container such as a
<fieldset>
element, and then setting
disabled
on the container.
The example below shows this in action. This is very similar to the previous example, except that the
disabled
attribute is set on the
<fieldset>
when the first button is pressed ? this causes all three buttons to be disabled until the two second timeout has passed.
<
fieldset
>
<
legend
>
Button group
</
legend
>
<
input
type
=
"
button
"
value
=
"
Button 1
"
/>
<
input
type
=
"
button
"
value
=
"
Button 2
"
/>
<
input
type
=
"
button
"
value
=
"
Button 3
"
/>
</
fieldset
>
const
button
=
document
.
querySelector
(
"input"
)
;
const
fieldset
=
document
.
querySelector
(
"fieldset"
)
;
button
.
addEventListener
(
"click"
,
disableButton
)
;
function
disableButton
(
)
{
fieldset
.
disabled
=
true
;
setTimeout
(
(
)
=>
{
fieldset
.
disabled
=
false
;
}
,
2000
)
;
}
Note:
Unlike other browsers, Firefox persists the
disabled
state of an
<input>
element even after the page is reloaded. As a workaround, set the
<input>
element's
autocomplete
attribute to
off
. (See
Firefox bug 654072
for more details.)