1

Possible Duplicate:
jQuery get textarea text

So i have a text area that takes the users input. How do i get text inside the text area and put it in my <div id="prev"> inside <p> tag? i tried using this:

function displayCustom() {
    var customText = $('textarea#custom').val();
    $('prev p').text(customText);   //<-- this doesnt work
    //alert(text); <-- if i try using this it works
}
Community
  • 1
  • 1
Chad D
  • 499
  • 1
  • 10
  • 17
  • Without HTML it's hard to tell what's going on, but you say you have "` – sachleen Oct 21 '12 at 23:05
  • 1
    Your selector is the problem `$('prev p')` what is prev? Are you trying to use jQuery's `.prev()` selector? or is prev a css class or ID? – Mark Oct 21 '12 at 23:07
  • i have div with id prev that contain

    inside it

    – Chad D Oct 21 '12 at 23:09
  • then use the selector `#prev` and it will work. `prev` is not a valid selector if you're targeting an ID. – Mark Oct 21 '12 at 23:09

2 Answers2

2

You should use # for the ID selector:

$('#prev p').text(customText); 
Ram
  • 143,282
  • 16
  • 168
  • 197
  • the other wrong point is getting the text area content ... not a complete answer – Reflective Oct 21 '12 at 23:07
  • @Reflective What is the complete answer? – Ram Oct 21 '12 at 23:08
  • This works thanks I forgot the # – Chad D Oct 21 '12 at 23:09
  • 1
    @Reflective Eh? The value of the `textarea` is taken correctly in the OP's code, since `alert(customText)` works fine. The answer is full and correct. – VisioN Oct 21 '12 at 23:10
  • following the good practices .text() or .html() should be used ... .val() is made for competability ... it will work but doesn't show a good style – Reflective Oct 21 '12 at 23:16
  • @Reflective Please read the docs. _The .val() method is primarily used to get the values of form elements such as input, select and textarea._ – Ram Oct 21 '12 at 23:17
  • form elements have diferent style - '.val()' normally represent attribute value which is not present in textarea ... value is present in input,select, button and many other ... but textarea is different `` ... so the good style requers to use .text() ... that's my oppinion – Reflective Oct 21 '12 at 23:21
  • @Reflective This is completely _wrong_, `val` reads the `value` _property_, what you are saying is `attr('value')`. – Ram Oct 21 '12 at 23:23
  • Note: At present, using .val() on textarea elements strips carriage return characters from the browser-reported value. If you have to getthe exact value you should use .html() – Reflective Oct 21 '12 at 23:38
-2

You can append your text inside <p> like this:

 var customText = $('#custom').val();
 $('#prev').append('<p>'+customText+'</p>');
Nelson
  • 49,283
  • 8
  • 68
  • 81
  • bad solution...assumes OP wants a new P tag and not replace content of an existing one. Only problem was a bad selector to begin with – charlietfl Oct 22 '12 at 01:13