简体   繁体   中英

Line break inside text area html

I'm making a form to fill in and create a pdf through, but I'm facing a problem with text area, I want the user to input text and while writting and pressing space to go back to line like this: 在此处输入图像描述

i want it to automatically show in the pdf but instead i get this: 在此处输入图像描述

how can i fix it? the code for this is:

<div class="mb-2"><textarea name="element" placeholder="Elements à fournir" class="form-control"></textarea></div>

You need to convert the line breaks from the textarea ( \r or \n ) into line breaks your PDF can understand ( <br /> <div> <li> etc).

a simple PHP way is

$string = nl2br($string);
// converts \n to <br />

If you need to transform those line breaks on the fly (like you're capturing the input and displaying it formatted as the user types), then do it in javascript. Here is a handy function taken from: https://stackoverflow.com/a/7467863/1772933

function nl2br (str, is_xhtml) {
    if (typeof str === 'undefined' || str === null) {
        return '';
    }
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}

Here is an example of how to use that function as the user is typing

$('#TextArea').keypress(function(evt){
        $('#TextArea').html(nl2br($('#TextArea').val())); // replace linebreaks first
        $('#pdfPreviewArea').html($('#TextArea').val()); // copy to #pdfPreviewArea
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM