How to enable and disable textarea with javascript?

Asked

Viewed 1,548 times

6

After searching the site, I found this question with solution, but the solution is in jquery!

When choosing option X need a field in specific is disabled and only be enabled again if another option is triggered!

I need this solution in JavaScript (every project is in Javascript).

<button id='btn_habilitar'>Habilita</button>
<button id='btn_desabilitar'>Desabilita</button>
<br>
<br>
<textarea id='obs' placeholder='Observação!'></textarea>

3 answers

8


What it takes to block/disable a textarea (or input) is the attribute/property disabled. So putting it with setAttribute or by removing it with removeAttribute you get the result you want. An example would be:

var textarea = document.getElementById('obs');
window.addEventListener('click', function(e) {
    var id = e.target.id;
    if (id == 'btn_desabilitar') textarea.setAttribute('disabled', true);
    else if (id == 'btn_habilitar') textarea.removeAttribute('disabled');
});

jsFiddle: https://jsfiddle.net/eo3nLfpp/

or simply via ownership of the DOM element

var textarea = document.getElementById('obs');
window.addEventListener('click', function(e) {
    var id = e.target.id;
    textarea.disabled = id == 'btn_desabilitar';
});

jsFiddle: https://jsfiddle.net/eo3nLfpp/1/

  • You do not think it bad to shoot the event on every screen ?

  • @Gabrielrodrigues in this case is an example. But more generally depends on the case and depends on the type of event. All events have capture and Bubbling. When you use delegation that’s what you do.

6

Just use the attribute document.getElementById("id").disabled:

function toggle(enable) {
  document.getElementById("obs").disabled = enable;
}
<button id='btn_habilitar' onclick="toggle(false)">Habilita</button>
<button id='btn_desabilitar' onclick="toggle(true)">Desabilita</button>
<br>
<br>
<textarea id='obs' placeholder='Observação!'></textarea>

3

You can do it like this:

Example:

var btn_habilitar = document.getElementById('btn_habilitar');
var btn_desabilitar = document.getElementById('btn_desabilitar');
var obs = document.getElementById('obs');


btn_habilitar.addEventListener("click", function() {
  obs.disabled = false;
});

btn_desabilitar.addEventListener("click", function() {
  obs.disabled = true;
});
<button id='btn_habilitar'>Habilita</button>
<button id='btn_desabilitar'>Desabilita</button>
<br>
<br>
<textarea id='obs' placeholder='Observação!'></textarea>

Detail:

Disabled does not pass the value to the form, and cannot edit.

Readonly sends the value to the form and also cannot edit.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.