0

On one side of my page, I have a very simple email form. On the other side I have a preview of the proposed email. For example:

enter image description here

As the user completes the fields, I'd like to update the preview on keyup. I wrote a little js function to do just that:

var email_previewer = function() {
  var fields = [
    { input: $('input#editor_invitation_to'), preview: $('dt.to') },
    { input: $('#editor_invitation_message'), preview: $('#message') }
  ];

  var perserve_linebreaks = function(text) {
    var html = text.replace(/\r\n\r\n/g, "</p><p>"),
      html = html.replace(/\r\n/g, "<br />"),
      html = html.replace(/\n\n/g, "</p><p>"),
      html = html.replace(/\n/g, "<br />"),
      html = "<p>"+html+"</p>";
    return html;
  };

  var sync_text = function(input, preview) {
    var text = input.val();
    if (input.is('textarea')) {
      text = perserve_linebreaks(text);
    }
    preview.text(text);
  }

  // sync preview on page load
  $.each(fields, function(index, field) {
    sync_text(field.input, field.preview);
  });

  // create keyup events
  $.each(fields, function(index, field) {
    field.input.keyup(function() {
      sync_text(field.input, field.preview);
    });
  });

}();

Everything works great except rails wants to escape my html and make it look like crap:

enter image description here

Normally, I know this is no problem: just add raw or html_safe. But I can't do that here since the markup is being dynamically built on keyup (or page load). Am I missing some simple solution? Any ideas for a workaround? My only idea is to load the preview in an iframe, which seems totally weird.

This is ridiculously frustrating. Someone please help!

1 Answer 1

1

I would immediately suspect preview.text(text) in your sync_text function. That should be creating a text node in the DOM, and what you want is to set the innerHTML so several nodes get created.

Sign up to request clarification or add additional context in comments.

1 Comment

try preview.html(text) instead of preview.text(text)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.