Submitting a form at intervals

I am trying to submit a form once a minute and have tried the following

setTimeout(function() {
  document.getElementById("form").submit();
}, 5000);

but I get document.getElementById(…).submit is not a function

I can’t figure out what I’m doing wrong.

(and I know 5000 is not a minute - that’s just for testing!)

Is your form written like this? If not, that won’t work…

<form id="form" ...>

Just that. (I tend to use original id’s :shifty: )

And you only have one id=“form” on the page? That error typically means

  • there is no id=“form” on the page
  • or there are more than one id=“form” on the page and it can’t tell which to grab.

There’s one and only one form with id form, but I’ve just realised I have the following JS as well:

(function () {
  const f = document.getElementById("form");
  const s = document.getElementById("submit");
  f.addEventListener("submit", function() {
    s.disabled = true;
    s.value = "Working...";
  });
})();

Not sure if this is interfering with it.

Try something like this:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Foo</title>
	<script>
		window.onload = function() {
			setTimeout(function() {
				let form = document.getElementById('Foo');
				if (form && typeof form.submit === 'function') {
					form.submit();
				} else {
					console.error('Form not found or submit is not a function');
				}
			}, 5000); // Change this to 60000 (60 seconds) for one-minute intervals
		};
	</script>
</head>
<body>
	<form id="Foo" action="/submit" method="post">
		... put your fields here ...
	</form>
</body>
</html>

Just to throw my hat in the ring

window.addEventListener('DOMContentLoaded', () => {
  const form = document.querySelector('#simple-form')

  form.addEventListener('submit', (event) => {
    event.preventDefault()
    // test with a console.log
    const {fname, lname} = event.currentTarget
    console.log(`${fname.value} ${lname.value}`)
  })

  const submitBtn = form.querySelector('input[type="submit"]')
  const timer = setInterval(() => submitBtn.click(), 5000)  
})

codepen example here

1 Like

It may be but doesn’t look like it’s stopping the form from being submitted. Just preventing it from being hit twice…oh, wait. Yeah, it might be stopping it the second time through…Try commenting out the disabled = true line…

1 Like