1

I have a small form that should run a js function when the submit button is clicked. Unfortunately, I keep getting an error in the console whenever the submit button is being clicked, that the function is not defined. The script file containing the function, is being integrated at the very bottom within the body tag and the external js script file

function test() {
  alert("this is a test");
}
<form name="form" class="text-center" novalidate onsubmit="return test()" method="POST">  
 <p>enter your name</p>

 <input type="text"  name="name" id="name">

 <button type="submit" class="btn">Submit</button>
</form>
Ali Esmailpor
  • 1,209
  • 3
  • 11
  • 22
DNYX
  • 43
  • 6
  • 3
    Your external file has a syntax error, as posted here at least. – Pointy Feb 14 '21 at 17:15
  • put it as alert("this is a test"); missing ) here. – Vinay Somawat Feb 14 '21 at 17:16
  • The next issue you'll run in to once you resolve this issue is the fact the form will submit. You may want to accept the `event` object into the `test()` function, and then `.preventDefault()`. [Reference](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) – Randy Casburn Feb 14 '21 at 17:23
  • Thanks I copied the code over having missed the other bracket. So, that cant be the issue. – DNYX Feb 14 '21 at 17:41

1 Answers1

1

The keyword "return" in your onsubmit means that the value expected to be returned is "false" or "true". It expects a boolean value to decide if the form will submit or not. If you only want to trigger the alert then you must do so without return, as in;

onsubmit="test()"

This has been extensively answered here - stackoverflow

mydogspies
  • 147
  • 1
  • 10
  • Hi, thanks for the link, but having only the function without the return in the onsubmit part, doesnt help either, still get the same uncaught reference error, that tells me that the function test is not defined. Also adding a return false doesnt help. It has nothing to do with the function itself but more as to how the function is being embedded into the html document containing the form. Hence the uncaught reference error saying the function is not defined that is being called in the onsubmit. I just dont know what to try out anymore. – DNYX Feb 14 '21 at 17:58
  • That probably means that you have not added the js script properly to your html page. Can you post your entire html page? – mydogspies Feb 15 '21 at 20:58