6

I thought this one was a simple one but I wasn't able to find anything out there, except one post here on STO.

Problem is the code doesn't work. I created a fiddle so you can see it for yourself.

Here is the code from the fiddle:

$('#someTextBox').keyup(function() {
    $('#target').html(this.val());
});

However, my HTML is a bit different than the example:

<textarea name="comment-box" id="comment-box" class="required"></textarea>
...
<p id="comment-preview"></p>

All I need help with is a way to display what's being typed on the textarea on the "comment-preview" container.

Any help guiding me on this one is greatly appreciated.

Community
  • 1
  • 1
Ricardo Zea
  • 9,505
  • 12
  • 71
  • 79

4 Answers4

17

Change this.val() to $(this).val()

DEMO: http://jsfiddle.net/FjNzS/1/

.val is a jQuery function and can be accessed from jQuery object. Inside the handler, this is DOM object and so you need to wrap it with $() to make it a jQuery object.

Selvakumar Arumugam
  • 78,145
  • 14
  • 119
  • 133
5

You can either use $(this).val() or this.value, but this.val() is incorrect.

elclanrs
  • 89,567
  • 21
  • 132
  • 165
2

You can also try this code with .on():

$('#someTextBox').on('keyup', function(){
    $('#target').html($(this).val());
}); 

Exemple http://jsfiddle.net/FjNzS/2/

RDK
  • 4,525
  • 2
  • 19
  • 28
1
$("#comment-box").keyup(function() {
    $("#comment-preview").text($(this).val());
});
Adam Moss
  • 5,347
  • 13
  • 45
  • 63