Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How click events work on disabled input field in javascript?

I have a disabled input tag in which the cursor property is text;

<input type="text" value='1111' style='cursor:text' disabled>

When I click on that input I want the disabled attribute to be removed. but things seems doesn't work.

input.addEventListener('click', function () {
input.disabled = false})
like image 480
Shihab Haque Avatar asked Sep 20 '25 16:09

Shihab Haque


2 Answers

Wrap the <input> in another element and bind the event to that. Add CSS property pointer-events: none to <input> so that the <label> is the only element recognizing the click, or mouse event (see Kaiido's comments).

document.querySelector('label').onclick = e => {
  const input = e.currentTarget.firstElementChild;
  input.disabled = false;
  input.style.pointerEvents = 'auto';
}
<label style='cursor: not-allowed'>
  <input type='text' style='cursor: text; pointer-events: none' value='Click to enable' disabled>
</label>
like image 65
zer00ne Avatar answered Sep 22 '25 07:09

zer00ne


How do click events work on disabled input field in javascript?

The spec says:

A form control that is disabled must prevent any click events that are queued on the user interaction task source from being dispatched on the element.

Because the disabled element isn't receiving the click event, you can wrap it in an element and add a click event listener to that wrapper instead:

Note that (as Kaiido pointed out in a comment), disabling pointer events on disabled elements is required to make this work according to spec, using the style declaration [disabled] { pointer-events: none; }

[disabled] { pointer-events: none; }
<label>
  <input type="text" value='1111' disabled />
</label>

<script type="module">

const label = document.querySelector('label');
const input = label.querySelector(':scope > input');

label.addEventListener('click', () => {
  input.disabled = false;
  input.focus();
});

</script>
like image 33
jsejcksn Avatar answered Sep 22 '25 09:09

jsejcksn