2

I just need the textarea's html markup in the DOM to reflect the value of the user input. (Edit: the user types something and it shows up when you hit "inspect element")

A contenteditable div was working fine but now it appears I'll need a textarea after all. Anybody know a way of doing this with javascript or html5?

jthomasbailey
  • 410
  • 1
  • 8
  • 19
  • Do you need the text area to be gone and replaced with the html markup? or do you need the html to be placed elsewhere in the dom? – lukek Nov 15 '12 at 01:12
  • No, I just need the DOM updated so I can grab it and use it for something else. A normal textarea doesn't update it's html when a user types something in it, whatever he types will be lost. – jthomasbailey Nov 15 '12 at 01:13

2 Answers2

5

I guess something like this will help you. Its using pure javascript and html5 data-value attribute:

  <textarea id="myTextArea" onkeyup="this.setAttribute('data-value', this.value);" data-value=""></textarea> 
Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57
1

This should work using text() function to escape the html from the user input :

$('textarea').on( 'blur' , function() 
{
    var textarea = $( this );
    textarea.next('span').text( textarea.val() );
});

with the following markup :

<textarea></textarea>
<span></span>​

The demo here : http://jsfiddle.net/UDfmm/

EDIT : If you want to keep the line breaks then do this

$('textarea').on( 'blur' , function() 
{
    var textarea = $( this );
    var span = textarea.next('span');

    var content = span.text( textarea.val() ).html();
    var content_with_br = content.replace(/\n\r?/g, "<br />");

    span.html( content_with_br );

});

Demo here : http://jsfiddle.net/UDfmm/3/

wakooka
  • 1,398
  • 10
  • 15