i'm trying use checkbox disable , enable textarea, toggling text in box @ same time. issue can't retain changes make when textarea enabled. textarea disabled , holds initial text. after textarea enabled, text becomes editable. if checkbox re-checked, changes disappear , orginal text re-appears-- toggling removes changes (which not want). i'd toggle text , forth, without removing changes. believe best way retain changes in variable? i've copied 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>
you don't need read value textarea
, store variable every time checkbox checked or unchecked. don't need (or should) set initial value textarea
in javascript. set initial textarea
content in html , use javascript attach event listener checkbox add/remove disabled
attribute element based on whether checked or not.
you can use onchange
attribute on html element , pass in javascript function had, imo doing unnecessarily couples html , javascript together; making harder make changes , 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 element's id var txtbox = document.getelementbyid('tjh'); var checkbox = document.getelementbyid('name1'); var customtext = 'initial text'; // attach event listener checkbox checkbox.addeventlistener('click', function(evt, el) { // if checked, save current textarea value , disable textarea if (evt.target.checked) { customtext = txtbox.value; txtbox.value = 'initial text'; txtbox.setattribute('disabled', evt.target.checked); } // otherwise restore text , reenable textarea removing disabled attribute html element else { txtbox.value = customtext ; txtbox.removeattribute('disabled'); } }, false) </script>
edit: added customtext variable store/restore txtbox values on disable/enable of checkbox
Comments
Post a Comment