Matteo
Matteo

Reputation: 8142

How to keep text inserted in a html <textarea> after a wrong submission?

Suppose I have a form like this:

<form action="page.php" method="post">

    Section1: <input name="section1" type="text"></br>
    Section2: <input name="section2" type="text"></br>

    Text:</br>
    <textarea name="post_text" cols="100" rows="20"></textarea>

    <input name="submit" type="submit" value="Submit">

</form>

Usually if I wish to save content inserted in a field of the form I would use this statement:

Section1: <input name="section1" type="text" vale="value="<?php echo $_POST['section1']; ?>""></br>

This way if I make a mistake in submission (error control code is not posted) the values inserted will be kept, and there is no need to reinsert them.

However using it in the textarea tag it will not produce the desired result.

Any ideas on how to do?

Thanks in advance!

Upvotes: 1

Views: 16104

Answers (4)

Marcis
Marcis

Reputation: 4617

Don't forget about htmlspecialchars(). This should help: https://developer.mozilla.org/en/HTML/Element/textarea

<textarea name="post_text" cols="100" rows="20"><?php echo htmlspecialchars($_POST['post_text']);?></textarea>

Upvotes: 6

pb149
pb149

Reputation: 2298

You would put it inside the <textarea> element like so:

<textarea name="post_text" cols="100" rows="20"><?php echo $_POST['post_text']; ?></textarea>

However, calling the $_POST element directly is not best practice. You should rather do something like this:

<textarea name="post_text" cols="100" rows="20">
<?php echo $var = isset($_POST['post_text']) ? $_POST['post_text'] : ''; ?>
</textarea>

This stops an E_NOTICE error from being reported upon the first page-load.

Upvotes: 0

veritas
veritas

Reputation: 2052

Use the $_POST variable like this.

<textarea name="post_text" cols="100" rows="20"><?= isset($_POST['post_text'])?$_POST['post_text']:'' ?></textarea>

the inline conditional checks if the $_POST['post_text'] is set to remove the NOTICE warning

Upvotes: 0

David Thomas
David Thomas

Reputation: 253496

You could use the same approach, but put the echo between the opening and closing <textarea></textarea> tags, as the textarea doesn't have a 'value' (as such) it has textual content:

<textarea name="post_text" cols="100" rows="20"><?php echo $_POST['textareaContent']; ?></textarea>

Upvotes: 5

Related Questions