Writing text on “div” using JavaScript

后端 未结 10 2415
难免孤独
难免孤独 2021-01-04 02:11

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




相关标签:
10条回答
  • 2021-01-04 02:24

    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.

    0 讨论(0)
  • 2021-01-04 02:24

    You'll have to prevent your form from submitting:

    <input type="submit" value="Ready!" onClick="writeComment(); return false;" />
    
    0 讨论(0)
  • 2021-01-04 02:25

    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;
    }
    
    0 讨论(0)
  • 2021-01-04 02:28

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

    Just return false from writeComment.

    0 讨论(0)
  • 2021-01-04 02:29

    Or another option is to convert your submit into a button and take it out of the form, buttons can now exist outside of forms and from the code you pasted I don't see why you have to use a form, this will mean that your page isn't reloaded when you click on the "Ready" button.

    0 讨论(0)
  • 2021-01-04 02:36

    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.

    0 讨论(0)
提交回复
热议问题