tags:

views:

53

answers:

2

How can I the HTML string <br> from this HTML FORM pass to the DIV using Jquery?

HTML FORM is:

<form action="" id="submit_wall" name="submit_wall" method="post">
<textarea cols="50" rows="5" id="message_wall"></textarea>
<button type="submit" id="fst" class="cfst">send</button>
</form>

 <div id="wall"></div>
 <div class="msg"></div>

Jquery code:

$(document).ready(function(){    
$("form#submit_wall").submit(function() {
var message_wall = $('#message_wall').attr('value');

$("div#wall").append('<div class=msg>'+ message_wall +'</div>');
return false; 
});
});

I'm trying using .html() but I keep getting error message.

A: 

First, as durilai commented, there is no div with an ID of wall, which means that even if your submit handler is working, append isn't going to append since there's nothing to append to.

Second, even though you said action="" on the form, the form will still submit and cause what looks like a page reload because you are not preventing the default action in your submit handler. One quick fix is to add return false; as the last line of the handler. Another fix is to rewrite it like:

$("form#submit_wall").submit(function(event) {
    event.preventDefault();

    $("div#wall").append("<div class='msg'>"+ $("#message_wall").val() + "</div>");
});
Lobstrosity
There are two DIV's in the HTML code but I forgot to put it in my question. Ok, now I edit it.I tried with 'var message_wall = $('#message_wall').val();' but there is no html line break '<br>' in the DIV as it is in the form text field.
Sergio
+1  A: 

Here is an example from learningjquery.com

$(document).ready(function() {
  $('#comment').one('focus',function() {
 $('#comment').parent().after('<div id="preview-box"><div class="comment-by">Live Comment Preview</div><div id="live-preview"></div></div>');
  });
  var $comment = ''; // that's two single quotation-marks at the end
  $('#comment').keyup(function() {
 $comment = $(this).val();
 $comment = $comment.replace(/\n/g, "<br />").replace(/\n\n+/g, '<br /><br />').replace(/(<\/?)script/g,"$1noscript");
 $('#live-preview').html( $comment );
  });
});

Which is very close of what you are trying to do.

Keyne
Thanks Keyne! This example is very helpful.
Sergio
Another quick way is to use `white-space: pre;` in the CSS for the div being appended to. Then you don't have to do <br> replacements. Then your original code should produce desired result.
Lobstrosity