Home > front end >  How click events work on disabled input field in javascript?
How click events work on disabled input field in javascript?

Time:07-29

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

CodePudding user response:

Wrap the <input> in another element and bind the event to that.

document.querySelector('label').onclick = e => 
  e.currentTarget.firstElementChild.disabled = false;
input {
  cursor: text;
}

[disabled] {
  cursor: not-allowed
}
<label>
  <input type='text' value='Click to enable' disabled>
</label>

CodePudding user response:

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:

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

  • Related