1

Desired outcome: define string var in PHP and echo it into textarea control as contents.

Problem: Textarea only contains:

    </body>
</html>

INDEX.PHP:

<?php
    $y = "Bonkers";
?>
<html>
<body>

    Here is a textarea control:<br />
    <textarea id='myText'  rows="30" cols="120" value='<?php echo $y; ?>' />

</body>
</html>
cssyphus
  • 37,875
  • 18
  • 96
  • 111

3 Answers3

12

The textarea element doesn't have a value attribute. This is how you should do it:

<textarea id='myText'  rows="30" cols="120"><?php echo $y; ?></textarea>
federico-t
  • 12,014
  • 19
  • 67
  • 111
  • Oh for Pete's sake... I copied someone else's code and just assumed... Thanks gents. – cssyphus Aug 15 '13 at 19:55
  • So why the weird behavior... Why not nothing (a blank textarea on page)? – cssyphus Aug 15 '13 at 19:55
  • 2
    Basically, it's because textarea isn't meant to be self-closing. Therefore, it reads the rest of the page looking for the closing textarea tag. That's why ` – Chris Forrence Aug 15 '13 at 20:01
  • Because you're not terminating your text area. Without a closing html tag, it's going to assume everything after the initial tag needs to be in the – JRizz Aug 15 '13 at 20:01
8

<textarea> doesn't have an HTML value attribute. Therefore, the correct way to set text within a textarea is as follows:

<textarea id="myText" rows="30" cols="120"><?php echo $y; ?></textarea>

You can access it within JavaScript or jQuery, however, as you would a normal input field.

// jQuery example
$("textarea#myText").val();

The reason why your textarea contains the ending body and html tags is due to how <textarea> is closed; it's only meant to be used as <textarea></textarea>, not <textarea />. (Reference)

Community
  • 1
  • 1
Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
  • 1
    don't forget about htmlspecialchars https://stackoverflow.com/questions/29112000/do-i-even-need-htmlspecialchars-for-textareas-value https://stackoverflow.com/questions/7632660/how-to-keep-text-inserted-in-a-html-textarea-after-a-wrong-submission – Charon ME Mar 27 '18 at 08:15
0

Do You Know !! You can echo something in textarea by using placeholder attribute also. Code is as follow.

<textarea placeholder="<?php echo $_SESSION['your_name']; ?>"></textarea>
Nagesh87
  • 9
  • 3
  • This won't actually put the text in the text area, it will only display the text until someone types something – maxpelic Apr 11 '19 at 13:52