JQuery Convert Html to text and back

If I had a text area on my web page for users to enter text, how would I convert that to show as html when the button is clicked and vice versa? I'm looking for something like what Wordpress will do when the user enters text and then converts it to html or can write html and convert it to text.

I tried several pieces of code:

var text_only = $('.snippet').text();

      

This only renders html without tags, this does not render html as expected and the rest are not much better

Edit: See link for better clarification - http://www.w3schools.com/html/tryit.asp?filename=tryhtml_basic_document

thank

Nick

+3


source to share


2 answers


Do you mean something like this? http://jsfiddle.net/7crysb0L/2

JS:

$('#dohtml').click(function() {

    var textAreaVal = $('#myTextArea').val();

    $('#myDiv').html(textAreaVal);

});

$('#dotext').click(function() {

    var textAreaVal = $('#myTextArea').val();

    $('#myDiv').text(textAreaVal);

});

      

html:



<textarea id="myTextArea" placeholder="Type here, then click the button to update the div"></textarea>
<br />

<button id="dohtml">Make HTML</button>
<button id="dotext">Make Text</button>
<div id="myDiv"></div>

      

The result is two buttons. Click Render HTML: to populate myDiv with HTML from the textbox and click Render Text to render the contents of the textarea as text and fill the div with visible HTML tags.

It's worth noting that this is not code that should be used in its current state, unless client-side, as it is very easy to insert unsafe values ​​- for example, try running a JS script, paste </textarea><script>alert('lol')</script>

in a textbox, then click Render HTML to find out why ... you don't want it to be somewhere in some way to save the unclean garbage, but if it's just for demo purposes, it should be fine.

jQuery html api ref: http://api.jquery.com/html/

+1


source


var text_only = '&lt;div&gt;' + $('.snippet').text() + '&lt;/div&gt';

      



Here's a fiddle: http://jsfiddle.net/p5hnttga/

0


source







All Articles