Search code examples
htmlforms

Can one input field be used by multiple forms without JavaScript?


Lets say I have a sign in form with two inputs, one for the email and one for the password. The form would have a sign in button which submits the email and password to the server to sign the user in. However, there is also a forgot password button on the page which when clicked should submit the email to the server to perform a different action like sending the reset password link to the email. In this scenario I have one input field (the email) which needs to be used by two separate forms. Is this possible to achieve somehow without the use of JavaScript?

Currently I have tried the following but it does not submit the email in the forgot password form

<form action="/sign-in" method="post" id="signInForm">
  <input type="text" form="signInForm forgotPasswordForm">
  <input type="password">
  <button type="submit">Log in</button>
</form>

<form action="/forgot-password" method="post" id="forgotPasswordForm">
  <button type="submit">Forgot password?</button>
</form>

Solution

  • Not entirely sure what your back end can or cannot do, but if you need to send <inupt> value to another endpoint use the formaction attribute.

    1. Place second <button> inside the same <form>
    2. Add name="action" to each <button>
    3. Add value="login" to the first <button>
    4. Add value="forgot" to the second <button>
    5. Add formaction="/forgot-password" to the second <button>

    If the second <button> is clicked, it will override <form action="/sign-in"> with it's formaction value of "/forgot-password". FYI, if a <button> is in a <form> it'll submit without a type attribute.

    Edit: Just read the comments and have added name and value attributes to each <button>. The server will get the value of either "login" or "forgot" under the key action.

    <form action="/sign-in" method="post" style="width:fit-content">
      <label> 
        Username <input name="user" required>
        Password <input name="pass" type="password">
        <button name="action" value="login">Log in</button>
      </label>
      <br>
      <button name="action"` formaction="/forgot-password" style="float:right" value="forgot">
        Forgot password?
      </button>
    </form>