Html textarea value as text only

Maybe the topic doesn’t really explain my problem correctly. I will try to explain a more accurate one here. So I have aragraph <textarea>and tags <p>. If I enter some text in textarea, and then after clicking the button, I insert the textarea value into the html item. If its text is all right, but if it is a manually written html code, it is not, because I do not want the browser to parse this html code. Here is a simple example: jQuery:

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

So how can I insert html code into text in a paragraph? Thanks in advance!

+3
source share
3 answers

Using the text method .

+3

HTML:

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

EDIT: .text(), , .

+4

, , , , ..

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

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

"foo <br> foo" . , ?

- -

.. JavaScripter, , :-) HTML, linebreaks <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>

, - , htmlents(). : -)

+1

Source: https://habr.com/ru/post/1731852/


All Articles