This is my test html code:
function setValue() {
$('.customTextAreaAuto').val($('.customTextAreaAuto').val() + "aaaaa\n");
}
$(function() {
$('.customTextAreaAuto').val(function() {
var currentVal = $(this).val();
if ($(this).outerHeight() > this.scrollHeight) {
$(this).height(1)
}
while ($(this).outerHeight() < this.scrollHeight) {
$(this).height($(this).height() + 1)
}
return currentVal;
}).trigger('change');
});
$(function() {
$('.customTextAreaAuto').on('input change', function() {
if ($(this).outerHeight() > this.scrollHeight) {
$(this).height(1)
}
while ($(this).outerHeight() < this.scrollHeight) {
$(this).height($(this).height() + 1)
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<textarea name="textarea" id="textarea" class="customTextAreaAuto">a
b</textarea>
<button onclick="setValue()">Click</button>
I use the "class" in jQuery and not "id" because in my case, the number of textarea will not be fix, depended on the data loaded the the page.
When input directly into , the height will automatically change to display all texts, but when click on button to change the value, the height does not change.
I know that I can add .trigger('change') to the code in function setValue(), but this is just a mock-up for changing value of textarea from another source. In my case, I am unable to use "trigger" when update the value due to design of the widget of the framework I used.
So, my question is how to let the textarea to know the value is changed to run the code that change the height.