David Reke
David Reke

Reputation: 555

Why is my button that calls a function on click making my page reload

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>

Upvotes: 0

Views: 37

Answers (3)

thopaw
thopaw

Reputation: 4054

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>

Upvotes: 0

Kudlas
Kudlas

Reputation: 659

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">

Upvotes: 1

David
David

Reputation: 218877

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.

Upvotes: 1

Related Questions