Enable text box when checkbox is checked

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 62

Enable text box when checkbox is checked

Hello,
I have this html code:

Code: Select all

<label><input type='checkbox' id='chb1' value='1' />Add text</label><br>
<textarea id='txta1' name='txta1' disabled></textarea>
Now, how can i have the textarea enabled only when the checkbox is checked? Is there a simple javascript to use?

Admin
Hello,
1. With javascript, register a 'click' event to the checkbox element.
2. In the function called by that click event check if the checkbox is enabled. If true, remove the 'disabled' attribute.

Code: Select all

<label><input type='checkbox' id='chb1' value='1' />Add text</label><br>
<textarea id='txta1' name='txta1' disabled></textarea>
<script>
var chb1 = document.getElementById('chb1');
var txta1 = document.getElementById('txta1');

if(chb1 && txta1){
  chb1.addEventListener('click', (e)=>{
    if(e.target.checked ===true) txta1.removeAttribute('disabled');
    else txta1.setAttribute('disabled', 'disabled');
  });
}
</script>
- Demo:


Similar Topics