Search code examples
jqueryhtmlline-breaks

replace linebreaks to get them working with jquery


I have following small script to preview some text before submitting it to store in a database:

jQuery(function($) {
    var input = $('#contents'),
    preview = $('#previewaccordion div.viewcontents');

    input.keyup(function(e) {
        preview.html(input.val());
    });
});

but if I type text with line-breaks it ignores them and writes all of them in one line. How could I replace the line-breaks so that they show correctly?


Solution

  • I assume that you are using a textarea for the input. There are \n used as linebreaks, which have no influence in HTML. So you have to replace them with br-tags:

    input.val().replace(/\n/g, "<br />");