0

I am working on a form that uses javascript to create a paragraph. For some reason, when I click my button, it forces my page to reload. Could you anyone let me know what I'm doing wrong here?

console.log('everything is linked')
function createParagraph() {
    console.log('function called');
    var wordOne=document.getElementById('textOne').value
    var wordTwo=document.getElementById('testTwo').value

    var paragraph = '<p>My first word is' + wordOne+'. My Second word is '+ wordTwo+'.</p>';

    document.getElementById('answer').innerHTML= paragraph
}
<body>
    <form action="">
        <input id='textOne' type="text">
        <input id='textTwo' type="text">
        <button onclick="createParagraph()">Click Me</button>
    </form>
    
    <div id="answer"></div>

    <script src="app.js"></script>
</body>
David Reke
  • 535
  • 1
  • 5
  • 20
  • 2
    Does this answer your question? [How do I make an HTML button not reload the page](https://stackoverflow.com/questions/1878264/how-do-i-make-an-html-button-not-reload-the-page) – Harmandeep Singh Kalsi Jul 09 '20 at 13:01

3 Answers3

1

The default behavior of a <button> inside a <form> is to submit that form. Set the button's type to explicitly not be a "submit":

<button type="button" onclick="createParagraph()">Click Me</button>

Additionally, if you have no use for the actual <form> (don't want to submit it) then it's probably best to just remove it:

<body>
    <input id='textOne' type="text">
    <input id='textTwo' type="text">
    <button type="button" onclick="createParagraph()">Click Me</button>
    
    <div id="answer"></div>

    <script src="app.js"></script>
</body>

That way there's nothing to accidentally be submitted in the first place.

David
  • 208,112
  • 36
  • 198
  • 279
1

Your button acts as a submit button, so your form is being submitted. To prevent this, you can use attribute onSubmit on your form and prevent sending form.

<form onSubmit="return false">
Kudlas
  • 659
  • 7
  • 24
0

Because the button is in a form and the form is probably submitted.

add the type="button" to not submit the form.

console.log('everything is linked')
function createParagraph() {
    console.log('function called');
    var wordOne=document.getElementById('textOne').value
    var wordTwo=document.getElementById('testTwo').value

    var paragraph = '<p>My first word is' + wordOne+'. My Second word is '+ wordTwo+'.</p>';

    document.getElementById('answer').innerHTML= paragraph
}
<body>
    <form action="">
        <input id='textOne' type="text">
        <input id='textTwo' type="text">
        <button type="button" onclick="createParagraph()">Click Me</button>
    </form>
    
    <div id="answer"></div>

    <script src="app.js"></script>
</body>
thopaw
  • 3,796
  • 2
  • 17
  • 24