最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How click events work on disabled input field in javascript? - Stack Overflow

programmeradmin2浏览0评论

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>

发布评论

评论列表(0)

  1. 暂无评论