Patrik
Patrik

Reputation: 1327

How to convert spaces and newlines from TEXTAREA to html

I need to convert spaces and new lines to <"br /"> and &nbsp. Convert text from TEXTAREA to DIV with same formating - and onClick convert text back to TEXTAREA with the same formating. How to do it ?

jsFiddle DEMO

HTML

<div id="meText"><br />Click to edit <br />this text.<br /> And this line has space &nbsp on the begining.<br />How to convert space to &nbsp ? <br /> <br /></div>

CSS

#meText{
    margin: 20px;
    width: 300px;
    height: 200px;
    background: red;
    font-family: Arial;
    font-size: 13px;
}
textarea {
    margin: 20px;
    font-family: Arial;
    font-size: 13px;
}

jQuery

$(function(){
    $("#meText").live('click',function(){
        var originalDiv = this;
        oldText = $(this).html().replace(/<br\s?\/?>/g,"\n");
        oldText = oldText.replace(/&nbsp;/g," ");
        $(this).replaceWith($("<textarea></textarea>").text(oldText).width($(this).width()).height($(this).height()).blur(function(){
            newText = $(this).val().replace(/\r\n|\r|\n/g,"<br />");

            //newText = newText.replace(/\n\s|\r\s|\r\n\s/g,"<br />&nbsp;");
            //newText = newText.replace(/\s\s/g,"&nbsp;&nbsp;");

            $(this).replaceWith($(originalDiv).html(newText));
        }));
    });
});

Upvotes: 0

Views: 5595

Answers (1)

Mr_Green
Mr_Green

Reputation: 41822

Do something like this: (javascript)

var x = "div to textarea";
var y = "textarea to div";

var div = document.getElementById('myDiv');
var txt = document.getElementById('myText');
var btn = document.getElementById('myBtn');
$(btn).click(function () {
    if (this.innerHTML == x) {
        txt.value = div.innerHTML.split('<br>').join('\n').split('&nbsp;').join(' ');
        div.innerHTML = "";
        btn.innerHTML = y;
    } else {
        div.innerHTML = txt.value.split('\n').join('<br>').split(' ').join('&nbsp;');
        txt.value = "";
        btn.innerHTML = x;
    }
});

Working Fiddle

I hope it atleast gives you idea.

Upvotes: 9

Related Questions