0

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.

braX
  • 11,506
  • 5
  • 20
  • 33
Sabyre
  • 97
  • 10

1 Answers1

1

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>
Ash
  • 11,292
  • 4
  • 27
  • 34
  • 1
    @Sabyre All good. I had no idea about `document.clear()` until now either. Apparently its deprecated anyway https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-clear: `The clear(), captureEvents(), and releaseEvents() methods must do nothing.` – Ash Jan 07 '20 at 01:50