with - search in html table using javascript




Writing text on “div” using JavaScript (7)

It is because you are submitting the form.

Quick fix:

<input type="submit" value="Ready!" onClick="writeComment()" />

to

<input type="button" value="Ready!" onClick="writeComment()" />

In addition, you are able to prevent the default action of an input. Basically telling the browser the you are going to handle the action with preventDefault:

function writeComment(e) {
    var comment = document.forma.commentUser.value;
    alert(comment);

    document.getElementById('comments').innerHTML = comment;
    e.preventDefault();
    return false;
}

I'm having some trouble whenever I want to add some text to my div tag, here's my code:

<html>

<body>
<div id="comments">

</div>
<form name="forma">
<textarea name="commentUser" id="commentUser" cols="40" rows="5">
Comments here...
</textarea><br>
<input type="submit" value="Ready!" onClick="writeComment()" />
</form>

<script type="text/javascript" >

function writeComment()
    {
    var comment = document.forma.commentUser.value;
    alert(comment);

    document.getElementById('comments').innerHTML=comment;


    }


</script>
</body>

</html>

It does what it has to do correctly, but then it switches back to the text box only and the comment I just wrote disappears. Any idea of what's going on here?

Thank you so much for your time.


Its making another request to the server, which is causing the page to be rendered again.

Just return false from writeComment.


This is because you use not just a regular button but a submit button which by default submits the form to the server. You can see that your comment is submitted via URL as you didn't specify the method(GET and POST and GET is default).

Simply write:

onclick="writeComment();return false;"

Returning FALSE prevents from default behaviour - submitting the form.


What's happening is your form is submitting, the page is refreshing, and the div is going back to its pre-JavaScript-set content.

Try swapping the type='submit' to 'button' on the button.


You'll have to prevent your form from submitting:

<input type="submit" value="Ready!" onClick="writeComment(); return false;" />

change this

<input type="submit" value="Ready!" onClick="writeComment()" /> 

to this:

<input type="submit" value="Ready!" onClick="writeComment(); return false;" /> 

you should switch
<input type="submit" value="Ready!" onClick="writeComment()" />
for
<input type="button" value="Ready!" onClick="writeComment()" />





html