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
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.
Here is a post that you can read about forms.
FormData will only use input fields that use the name attribute.
Please update html as following.