We have a form with username password inputs and a button. When button is clicked, the form redirects to another url by adding /?
to the url current, which is unwanted behavior.
In case we add event.preventDefault()
, it prevents the browser from offering to save the username and password (see the picture below, what i mean).
Here is the code. It does not redirect here, because it is inside a snippet.
document.getElementById('send').addEventListener('click', (event) => {
//event.preventDefault()
console.log('test')
})
<form>
<div>
<label for="username">username</label>
<input
id="username"
type="text"
autocomplete="username"
/>
<label for="password">password</label>
<input
id="password"
type="password"
autocomplete="new-password"
/>
</div>
<button id="send">send</button>
</form>
I tried to use div
instead of form
tag, but it prevents autocomplete from working too.
Also, here you can test the form with browser offering to save password. Copy the code from here
How to prevent redirect on button click and preserve browser's autocomplete functionality?