Prefilling a textarea with data pulled from a DB.
<textarea name="body" id="body" rows="5" cols="70"><? echo $body; ?></textarea>
I have a clear button to make it easier for the user to wipe a large chunk of text without having to highlight and delete.
The button uses an onclick="clear();"
function call.
Here is the function…
function clear() {
$('#body').val('');
}
The problem is it wont clear the predefined text. It will only clear text typed in addition to the predefined text. Or if I manually remove the predefined text it works fine.
I need the field to show the value from the DB. Is there a way to accomplish this without echoing the DB value in a <div>
above the field and refraining from pre-defining the ext in the textarea?
Thanks.
Advertisement
Answer
Rename your function to be something other than clear()
and the rest is good. See Why can’t I call a function named clear from an onclick attribute?
Alternatively use .on('click', ...)
as I’ve demonstrated below by attaching the event listener to the button using the class js-clear
.
function myClear() {
$('#body').val('');
}
$('.js-clear').on('click', function() {
$('#body').val('');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea name="body" id="body" rows="5" cols="70">test content</textarea><br>
<button onclick="myClear()">myClear</button>
<button class="js-clear">.on('click')</button>