当用户点击“提交” - javascript或php时,使用textarea上面的文本创建一个新的div

问题描述:

I am asking if someone can give me a simple javascript code that will place the text written by a user in a textarea into a new div created when the user clicks on submit button.

Here is the form:

       <form id="myForm" class="myForm" action="profile.php" method="post" target="hidden-form" >

Write text here: 
<textarea name="comment" id="comment" placeholder="comment here" rows="1" cols="40" ></textarea>
<input type="submit" name="submit" id="submit" value="submit" "/>
</form>
<IFRAME style="display:none" name="hidden-form"></IFRAME> 

Try this out:

<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js">    </script>
<script type="text/javascript" >
    function updateDiv()
    {
        var x = $('#comment').val();
        $( "#UserCommentsDiv" ).append("<div>" + x + "</div>");
    }
</script>
</head>
<body>
    <form id="myForm" class="myForm" action="profile.php" method="post" target="hidden-form" >
        Write text here: 
        <textarea name="comment" id="comment" placeholder="comment here" rows="1" cols="40" ></textarea>
        <input type="submit" name="submit" id="submit" value="submit" onclick="updateDiv();"/>
    </form>

    <div id="UserCommentsDiv"></div>
    <IFRAME style="display:none" name="hidden-form"></IFRAME> 
</body>
</html>

DEMO

Maybe with something like this in profile.php

<?php 

$comment = $_POST['comment'];

?> 

Then add this in your div where you want.

<?php echo $comment; ?>

Here is the pure javaScript solution

HTML

<form >
<div id="container">
<textarea name="comment" id="comment" placeholder="comment here" rows="1" cols="40" ></textarea>
<br />
<input type="button" name="submit" id="submit" value="submit" onclick="storeData()"/>
</div>

</form>

javaScript

function storeData(){
    var commentTag = document.getElementById('comment');

    var newDiv = document.createElement('div');
    newDiv.id = "result";
    newDiv.innerHTML = commentTag.value;

    var submitTag = document.getElementById('submit');
    parDiv = document.getElementById('container');
    container.insertBefore(newDiv, submitTag);
}

UPDATE

When use in form your input type should be button instead of submit

Shuld be

<input type="button"

instead of

<input type="submit"

DEMO