简体   繁体   中英

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>

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.

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM