最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Get the exact contents of a textarea using javascript - Stack Overflow

programmeradmin0浏览0评论

I have a text area that looks like this:

<textarea id="txtBody" name="txtBody">q2312312312<strong>313213213</strong>21231321231231 &lt; &amp;lt;</textarea>

When I do this in javascript:

var t = document.getElementById('txtBody').value;

I get this back:

<p>q2312312312<strong>313213213</strong>21231321231231 < &lt;</p>

Seems like it should just give me the exact characters as they are... am I missing something? Is there a way to get the exact characters out of a text area?

I have a text area that looks like this:

<textarea id="txtBody" name="txtBody">q2312312312<strong>313213213</strong>21231321231231 &lt; &amp;lt;</textarea>

When I do this in javascript:

var t = document.getElementById('txtBody').value;

I get this back:

<p>q2312312312<strong>313213213</strong>21231321231231 < &lt;</p>

Seems like it should just give me the exact characters as they are... am I missing something? Is there a way to get the exact characters out of a text area?

Share Improve this question edited Apr 29, 2011 at 18:48 jjxtra asked Apr 29, 2011 at 18:38 jjxtrajjxtra 21.2k17 gold badges106 silver badges146 bronze badges 1
  • What's interesting is that getting innerHTML returns: q2312312312&lt;strong&gt;313213213&lt;/strong&gt;21231321231231&amp; &lt; &amp;lt; – mVChr Commented Apr 29, 2011 at 18:42
Add a ment  | 

2 Answers 2

Reset to default 4

am I missing something?

& is HTML for "Start an entity".

When you put the text into the HTML document (between the start and end tags for the textarea), you are failing to represent that text as HTML.

As a result, the browser performs error recovery and treats <strong> as "A less than character, the word strong, then a greater than character" (because tags are not allowed inside a textarea element, but treats &lt; as "A less than character" because there isn't a machine detectable error here.

Is there a way to get the exact characters out of a text area?

You need to write the HTML correctly in the first place.

<textarea id="txtBody" name="txtBody">q2312312312&lt;strong&gt;313213213&lt;/strong&gt;21231321231231 &amp;lt; &amp;amp;lt;</textarea>

I get the right contents, I guess your (X)HTML is not valid...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3/1999/xhtml" xml:lang="en" lang="en">

<head>
    <title>untitled</title>
    <meta http-equiv="content-type" content="text/html;charset=utf-8" />
    <meta name="generator" content="Geany 0.19.1" />
</head>

<body>
    <textarea id="txtBody" name="txtBody">q2312312312<strong>313213213</strong>21231321231231& &lt; &amp;lt;</textarea>
    <script>
        var t = document.getElementById('txtBody').value;
        alert(t);
    </script>
</body>

</html>
发布评论

评论列表(0)

  1. 暂无评论