skip to Main Content

I have an html page with a form and a js script with a listener on a button.

<html>
  <head>
    <script type="text/javascript" src="login.js" defer></script>
  </head>
  <body>
    <form id="form">
      <table>
        <tr>
          <td>Username</td>
          <td><input type="text" id="user" value=""></td>
        </tr>  
        <tr>
          <td>password</td>
          <td><input type="text" id="pass" value=""></td>
        </tr>
      </table>
      <button type="button" id="btn">send</button>
    </form>
  </body>
</html>
const form = document.getElementById("form");
const btn = document.getElementById("btn");

btn.addEventListener("click", (e) => {
  const payload = new FormData(form);

  console.log([...payload]);
})

the result from console log is:
[] [[prototype]]:array(0)

Somebody knows why formdata is empty?

I have tried also like this

const form  = e.target.closest('form');

same result.
If I log document.getElementById("user").value it prints the value, so something in the formdata should be.

2

Answers


  1. I believe that you want to make your submit button have a type of ‘submit’ and then having your event listener listen to the ‘submit’ event on your form.

    const form = document.getElementById('form')
    console.log(form);
    form.addEventListener("submit", (event) => {
      const data = new FormData(event.target);
      const name = data.get("name");
      console.log(name);
    });
    <form id="form">
      <input type="text" name="name" value=""/>
      <button type="submit" id="btn">Save</button>
    </form>

    Here is a post that you can read about forms.

    Login or Signup to reply.
  2. FormData will only use input fields that use the name attribute.
    Please update html as following.

    <html>
      <head>
        <script type="text/javascript" src="login.js" defer></script>
      </head>
      <body>
        <form id="form">
          <table>
            <tr>
              <td>Username</td>
              <td><input type="text" id="user" name="user" value=""></td>
            </tr>  
            <tr>
              <td>password</td>
              <td><input type="text" id="pass" name="pass" value=""></td>
            </tr>
          </table>
          <button type="button" id="btn">send</button>
        </form>
      </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search