简体   繁体   中英

Convert Enter as new line from textarea tag into div tag

Shema

How I should convert new line when user press enter key as <br> tag inside <div> tag for result?

here's the codes:

<textarea>
    First text here //user press enter here 
    Second text here
</textarea>  

//AJAX to insert text to Database here... 

MySQL Procces

//AJAX repond here... 

document.getElementById('sample').innerHTML = this.responseText;

Result inside <div> tag

<div id='sample'>
    First text here <br/>
    Second text here
</div>

use nl2br function in php:

$text = nl2br($POST['text_field']);

in javascript:

function nl2br (str, is_xhtml) {   
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');
}

You can use replace() to replace the enter( \\n ) to <br>

Stack Snippet

 var text = document.getElementById("text"); var result = document.getElementById("result"); text.addEventListener("keyup", function(e) { result.innerHTML = text.value.replace(/\\n/g, "<br />"); }); 
 <textarea id="text"></textarea> <div id="result"></div> 

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