admin管理员组

文章数量:1326461

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})

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})
Share Improve this question asked Jul 29, 2022 at 0:58 Shihab HaqueShihab Haque 654 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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 ments).

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>

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 ment), 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>

本文标签: htmlHow click events work on disabled input field in javascriptStack Overflow