0

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).

prompt to save the password

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?

Daniel
  • 1,431
  • 2
  • 16
  • 36
  • Why do you use these values in `autocomplete`? – Raxel21 Oct 11 '20 at 00:48
  • @Raxel21 these values are in order for the browser to save a password. Please take a look here: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete – Daniel Oct 11 '20 at 00:52

3 Answers3

0

To prevent redirection on button click, set the type="button" for the button element and that will turn the button element to just an ordinary button, then after then you know that you will be using AJAX to submit the form:

<button id="send" type="button">send</button>

is this the answer you are looking for

Paulos Ab
  • 319
  • 4
  • 16
  • I have tried your solution, but it does not work. It does not redirect, but it makes autocomplete not to work, the same, as `event.preventDefault`. – Daniel Oct 11 '20 at 01:03
0

The 'new-password' value used for autocomplete should be preventing autofill since the browser is expecting a new password to be entered there. According to the MDN:

Preventing autofilling with autocomplete="new-password"

If you are defining a user management page where a user can specify a new password for another person, and therefore you want to prevent autofilling of password fields, you can use autocomplete="new-password".

I think this answer may help

Krfisc62
  • 3
  • 2
0

I have not checked. But you can try this:

document.getElementById('send').addEventListener('click', (event) => {
  console.log('test');
  return false;
})