Ad

Toggle Textarea Text, But Retain Changes To The Text

- 1 answer

I'm trying to use a checkbox to disable and enable a textarea, toggling text in the box at the same time. My only issue is that I can't retain the changes that I make when the textarea is enabled. The textarea is disabled initially and holds initial text. After the textarea is enabled, the text becomes editable. If the checkbox is re-checked, the changes disappear and the orginal text re-appears-- toggling back removes the changes (which is not what I want). I'd like to toggle the text back and forth, but without removing the changes. I believe that the best way to do this is to retain the changes in a variable? I've copied the code below:

 function toggleDisabled(_checked) {
document.getElementById('tjh').disabled = _checked ? true : false;
document.getElementById('tjh').value= "initial text";
}

    <form>
    <input type="checkbox" checked name="name1"     onchange="toggleDisabled(this.checked)"/>
<textarea disabled name="name2" id="tjh">initial text</textarea>
</form>
Ad

Answer

You don't need to read the value from the textarea and store it into a variable every time the checkbox is checked or unchecked. You also don't need to (or should) set the initial value for the textarea in your javascript. Set the initial textarea content in the HTML and then use javascript to attach event listener to the checkbox that will add/remove the disabled attribute from the element based on whether checked or not.

You can use the onChange attribute on the HTML element and pass in a javascript function as you originally had, but IMO doing so unnecessarily couples the HTML and Javascript together; making it harder to make changes and read.

<form>
  <input type="checkbox" checked name="name1" id='name1' />
  <textarea disabled name="name2" id="tjh">Initial text</textarea>
</form>



<script type='text/javascript'>
  
  // Grab HTML elements by element's id
  var txtBox = document.getElementById('tjh');
  var checkBox = document.getElementById('name1');
  var customText = 'initial text';

  // Attach event listener to checkbox
  checkBox.addEventListener('click', function(evt, el) {

    // If checked, then save current textarea value and disable textarea
    if (evt.target.checked) {
      customText = txtBox.value;
      txtBox.value = 'initial text';
      txtBox.setAttribute('disabled', evt.target.checked);
    }

    // Otherwise restore text and reenable the textarea by removing disabled attribute from HTML element
    else {
      txtBox.value = customText ;
      txtBox.removeAttribute('disabled');
    }
  }, false)
</script>

EDIT: Added customText variable to store/restore txtBox values on disable/enable of checkbox

Ad
source: stackoverflow.com
Ad