开发者

Textarea value to paragraph html as text only

开发者 https://www.devze.com 2022-12-20 00:09 出处:网络
Maybe topic really doesn\'t explain my problem correctly. I\'ll try to explain more precise it here.

Maybe topic really doesn't explain my problem correctly. I'll try to explain more precise it here. So I'am having a <textarea> and <p> aragraph tags. If I'am entering some text in textarea, and then after button click I insert textarea value into paragraph html. If its text everything is fine, but if it's a hand written html code, its not right, because I don't want browser to parse that html code. Here is some simple example involved jQuery:

$('.some_button').click(function () {
$('p').html($('textarea').val());
});

So how I can insert html code as text to paragraph? T开发者_如何学运维hanks in advance!


You need to escape the HTML:

$('p').html($('textarea').val().replace(/</g,'&lt;').replace(/>/g,'&gt;'));

EDIT: use .text() instead as already mentioned unless you want to do a manual conversion.


With the text method.


David Dorward answered this already, and I'd have added a comment instead of an answer but wasn't sure the code would show up right, so.. With this

$('.some_button').click(function () {
  $('p').text($('textarea').val());
});

and

<input type='button' class='some_button' value='click!'><br>
<textarea>foo&lt;br&gt;foo</textarea>
<p></p>

Clicking the button shows "foo<br>foo" in the paragraph. Is that what you need?

--Addendum--

Ok.. I am only a starting JavaScripter, so not sure how bad this is :-) But the following replaces special characters by their HTML equivalents while replacing linebreaks with a <br>.

<script type="text/javascript">
String.prototype.htmlents = function() {
  var trans = {'&':'&amp;', '"':'&quot;', '\'':'&#039;', '<':'&lt;', '>':'&gt;'};
  var arr = this.split('');
  for (var i=0;i<arr.length;i++) {
    if (trans.hasOwnProperty(arr[i])) {
      arr[i] = trans[arr[i]];
    }
  }
  return arr.join('');
};

$(document).ready(function(){
  $('.some_button').click(function () {
    $('p').html($('textarea').val().htmlents().replace(/\n/g,'<br>\n'));
  });
});
</script>

Remembered I've had to do something similar before, and still had the htmlents() lying around from that time. Feel free to criticise :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号