Using val () in script causes me to lose line breaks

1

I have a problem. I'm implementing a chat page using the following script:

<script>
        $(document).ready(function(){
                $("#enviar").click(function(){
                    var mensagem = $("#campodetexto").val();
                    var old = $("#conteudojanela").html();
                    var hora = (new Date).getHours();
                    var min = (new Date).getMinutes();
                    if(min <10)
                        min = "0"+min;
                    var sec = (new Date).getSeconds();
                    if(sec <10)
                        sec = "0"+sec;
                    var horario = hora+":"+min+":"+sec;
                    var nmsg = old + "<div class=\"user\"><div class=\"colunm01\"><p class=\"atendenteBold\">Cliente</p><p>"+horario+"</p></div><div class=\"colunm02\"><p>"+mensagem+"</p></div></div>";
                    $("#conteudo").html(nmsg);
                });
        });
        </script>

What happens is that I lose all the line breaks I make when I type the text. Changing the call from var mensagem = $("#campodetexto").val(); to .text(); or .html(); makes me lose the value, and calling replace() has not worked with exchanges between \n , \n and / or <br> .

I know I'm doing something wrong, I need to know just what it is. I already searched dozens of tutorials on the internet and nothing helped me.

Thank you in advance.

------ EDIT: What I want is that when entering a text in the chatbox ( "#campodetexto" ), the text goes to the chat screen ( "#conteudo" ) with all line breaks ( [ENTER] ) that I have typed, and this does not had happened. The line break is shown in the chatbox, but not in the chat window.

    
asked by anonymous 17.11.2014 / 19:01

1 answer

8

What you can do is .replace of \n and <br /> to be interpreted correctly:

var mensagem = $("#campodetexto").val();
var text = mensagem.replace(/\r?\n/g, '<br />');

Then, instead of using .html as you are using, just use .append to add text to your chat:

$("#conteudo").append($('<br/><label>'+horario+': '+text+'</label>'))

Complete code:

$("#enviar").click(function(){
    var mensagem = $("#campodetexto").val();

    var hora = (new Date).getHours();
    var min = (new Date).getMinutes();
    if(min <10)
        min = "0"+min;
    var sec = (new Date).getSeconds();
    if(sec <10)
        sec = "0"+sec;
    var horario = hora+":"+min+":"+sec;

    var text = mensagem.replace(/\r?\n/g, '<br />');

    $("#conteudo").append($('<br/><label>'+horario+': '+text+'</label>'))
});

LINK JSFiddle

    
17.11.2014 / 19:28