7

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
  • 10,053
  • 13
  • 76
  • 79

4 Answers4

18

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
  • 79,297
  • 15
  • 120
  • 134
5

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

elclanrs
  • 92,861
  • 21
  • 134
  • 171
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,540
  • 2
  • 20
  • 29
1
$("#comment-box").keyup(function() {
    $("#comment-preview").text($(this).val());
});
Adam Moss
  • 5,582
  • 13
  • 46
  • 64