Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery serialize error with textarea filed

I'm using this function, to submit form in the background, with custom messages. It works perfectly, except with textarea fields. I've read that the serialize function has problems with ex. linebreaks.

 $(function() {
      $("#comment_form").validate({    submitHandler: function(form) {
        $.post('/u/r/l/', $("#comment_form").serialize(),
 function(data) {
            $('#comment_container').html(data);
                });
            }
        });

The textarea is a markitup! editor area.

like image 254
wintercounter Avatar asked Nov 06 '10 22:11

wintercounter


1 Answers

As stated here: http://api.jquery.com/serialize/#comment-67394779

function keepLB (str) { 
  var reg=new RegExp("(%0A)", "g");
  return str.replace(reg,"%0D$1");
}

$(function() {
  $("#comment_form").validate({ submitHandler: function(form) {
    $.post('/u/r/l/', keepLB($("#comment_form").formSerialize()), function(data) {
      $('#comment_container').html(data);
    });
  }
});

If it doesn't work, manually urlencode the textarea data:

$(function() {
  $("#comment_form").validate({ submitHandler: function(form) {
    $.post('/u/r/l/', "textareadata="+escape($("#mytextarea").value), function(data) {
      $('#comment_container').html(data);
    });
  }
});

And if you also want to send other form contents (note: don't give the textarea a "name" here, just an id!):

$(function() {
  $("#comment_form").validate({ submitHandler: function(form) {
    $.post('/u/r/l/',
    $("#comment_form").formSerialize()+"&textareadata="+escape($("#mytextarea").value),
    function(data) {
      $('#comment_container').html(data);
    });
  }
});
like image 145
thejh Avatar answered Sep 26 '22 14:09

thejh