javascriptjqueryhtml

Uncaught ReferenceError: submitted is not defined


I am attempting to run a function only if a submit button has been pressed (which sets the integer value of the variable submitted to 1), however I am receiving this error in the console and the function isn't running after the variable being set to 1:

Uncaught ReferenceError: submitted is not defined

$("form#form1").submit(function(event) {
      event.preventDefault();
      var submitted = 1; // set the integer value of the variable submitted to 1
});

if (submitted == 1) { // if the integer value of the varialbe is 1
   // run a function
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1">
  <input type="submit">
</form>


Solution

  • You should just put the call to the function right in the callback of the submit action:

    $("form#form1").submit(function(event) {
      event.preventDefault();
      // run a function here
    });
    

    This way the function will be called right after the form is submitted.