'jquery - Updating and clearing textarea not working when content edited
Can someone please support with the code snippet. There are li items. The button "update" updates the textarea content with defined text (data-text). The text area has 2 buttons that copy and clear the textarea content. What doesn't work is when the text in the textarea is edited: Neither do the "update" buttons work nor the clear button. The "copy" button still works. What needs to be changed in the code?
jQuery(function ($) {
$('.area_update').click(function () {
var my_var = $(this).data('text');
$('#area').html(my_var);
document.querySelector("textarea").select();
document.execCommand('copy');
});
});
jQuery(function ($) {
$('#clear_area').click(function () {
$('#area').empty();
});
});
document.querySelector("#copy-btn").onclick = function () {
document.querySelector("textarea").select();
document.execCommand('copy');
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>aaa<input type="button" class="area_update" data-text="zzz" value="update" /></li>
<li>bbb<input type="button" class="area_update" data-text="yyy" value="update" /></li>
<li>ccc<input type="button" class="area_update" data-text="xxx" value="update" /></li>
</ul>
<textarea id='area' name='editor'>test</textarea>
<button id="copy-btn">Copy</button>
<button id="clear_area">Clear</button>
Solution 1:[1]
To change the content of the textarea you should use .val() instead of .html(). Try this
jQuery(function ($) {
$('.area_update').click(function () {
var my_var = $(this).data('text');
$('#area').val(my_var);
document.querySelector("textarea").select();
document.execCommand('copy');
});
});
jQuery(function ($) {
$('#clear_area').click(function () {
$('#area').val('');
});
});
document.querySelector("#copy-btn").onclick = function () {
document.querySelector("textarea").select();
document.execCommand('copy');
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>aaa<input type="button" class="area_update" data-text="zzz" value="update" /></li>
<li>bbb<input type="button" class="area_update" data-text="yyy" value="update" /></li>
<li>ccc<input type="button" class="area_update" data-text="xxx" value="update" /></li>
</ul>
<textarea id='area' name='editor'>test</textarea>
<button id="copy-btn">Copy</button>
<button id="clear_area">Clear</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ruleboy21 |
