The page will refresh after a form submit event and this is the default behavior of HTML forms. Therefore the page will reset to default and the checkbox will be unchecked if you have checked it.
Here’s how you can fix this issue:
Code of index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="./script.js"></script> </head> <body> <div> <form onsubmit="onSubmit(event)"> <input type="checkbox" /> <span class="text-white">Filter</span> <div> <button type="submit">Submit</button> </div> </form> </div> </body> </html>
Code of script.js:
const onSubmit = (event) => { event.preventDefault(); console.log("on submit called"); }
So, when we click on the submit button, the onSubmit() method will be executed. Here, we are passing event object in the argument of onSubmit() method which has a built-in preventDefault() method to prevent page from getting refreshed after form submission.