Home > other >  How to prevent form submission on wrong button and only work on right button
How to prevent form submission on wrong button and only work on right button

Time:09-28

I've made a codesandbox to showcase the behaviour: https://codesandbox.io/s/musing-dan-ejyuv

I have two buttons in my form one is forgot password and other is the submit button itself. When I enter values and press enter it registers the forgot password button for no reason even when the submit button has input type="submit". How can I get rid of this behaviour and prevent it to go on the forgot password page but instead it should be submitting the form.

CodePudding user response:

You need to add the type=button to the forgot passwrod button. As per MDN docs for button mentions

If this attribute is not set, the <button> is associated with its ancestor <form> element, if any.)

Once you add the type=button to the forgot password, it'll not behave as submit button.

<button
  type="button"
  onClick={() => {
    setForgotPassword(true);
  }}>
  Forgot Password?
</button>

Updated Sandbox link

CodePudding user response:

          <button
            onClick={(e) => {
              e.preventDefault();
              setForgotPassword(true);
            }}
          >
            Forgot Password?
          </button>
  • Related