Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing text on "div" using JavaScript

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.

like image 292
Raúl Núñez Cuevas Avatar asked Aug 25 '11 19:08

Raúl Núñez Cuevas


4 Answers

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;
}
like image 100
Joe Avatar answered Sep 29 '22 20:09

Joe


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.

like image 33
n8wrl Avatar answered Sep 29 '22 22:09

n8wrl


When you click on the submit button the form is submitted, causing the whole page to reload. You need to return false from the onclick of the submit button to prevent it:

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

Or, if you don't want the button to ever submit the form change type="submit" to type="button".

PS. It's bad practice to use the onclick attribute. Instead bind a handler to the click event using pure JS.

like image 41
Paul Avatar answered Sep 29 '22 20:09

Paul


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.

like image 25
lukas.pukenis Avatar answered Sep 29 '22 20:09

lukas.pukenis