0

I have this code and it isn't working the way i want. I want it to create a new div under the other one everytime the button is clicked, but it is just changing the content of the div. help

<!DOCTYPE html>
<html>
<head>
<style>
p{
background-color: red;
font-family: arial;
}
</style>
</head>
<body>

Name: <textarea id="myText" value=""></textarea>

<button type="button" onclick="myFunction()">Enviar</button>

<div id="demo"></div>

<script>
function myFunction() {
    var x = document.getElementById("myText");
    var defaultVal = x.defaultValue;
    var textoComentario = x.value;

    if (defaultVal == textoComentario) {
        alert("Digite um comentário!");
    } else {
           document.getElementById("demo").innerHTML =  "<p>" + textoComentario + "</p>";
        x.value = "";

    }
}
</script>

</body>
</html>

3 Answers3

0

You can try with jquery more easily:

 $('<div/>').html(textoComentario).appendTo('#demo');

EDIT

You can make it with pure-javascript with createElement too:

http://www.w3schools.com/jsref/met_document_createelement.asp

Good luck!

Marcos Pérez Gude
  • 20,206
  • 4
  • 34
  • 65
0

I think you are looking for this:

WORKING:DEMO

HTML

NO CHANGE

CSS

NO CHANGE

JS/JQuery

function myFunction() {
    var x = document.getElementById("myText");
    var defaultVal = x.defaultValue;
    var textoComentario = x.value;
    alert(textoComentario);

    if (defaultVal == textoComentario) {
        alert("Digite um comentário!");
    } else {
           $("#demo").css("display","block");
           $("#demo").append("<p>" + textoComentario + "</p>");
        x.value = "";

    }
}
divy3993
  • 5,335
  • 2
  • 23
  • 37
0

Replace your

document.getElementById("demo").innerHTML =  "<p>" + textoComentario + "</p>";

into $('#demo').append("<p>" + textoComentario + "</p>");

It will work.......

Vignesh Bala
  • 859
  • 6
  • 24