How to enable and disable textarea with javascript?

6

After performing a search on the Site, I found this question with solution , but the solution is in jquery !

When choosing option X, I need a specific field to be disabled and only be enabled again if another option is activated!

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>
    
asked by anonymous 05.02.2016 / 16:55

3 answers

8

What it takes to block / disable a textarea (or input ) is the disabled attribute / property. So by putting it with setAttribute or removing it with removeAttribute you will 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: link

or simply via property 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: link

    
05.02.2016 / 16:59
6

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

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>
    
05.02.2016 / 16:58
3

You can do 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, in addition to being unable to edit.

Readonly sends the value to the form and can not edit either.

    
05.02.2016 / 17:01