How do I prevent the form from being submitted in front of the DOM?

I am using javascript for form validation,

but cannot handle the case where the form is submitted before the DOM is ready

I tried:

<form method="POST" disabled="disabled">
<input type="submit" />
</form>

      

But the form can still be submitted.

+2


source to share


4 answers


Just check before submission only to prevent posting before the House is ready.



<form method="POST" onsubmit="return handle()">
    <input type="submit" />
</form>

<script>

   function handle()
   {
       return imReady;
   }

   var imReady = false;
   function setReady()
   {
      imReady = true;          
   }

   // edit: add this line
   window.onDomReady = setReady();
</script>

      

+1


source


One way of holding down would be to leave the submit button (or form) disabled and enable it in an event window

or body

onload

. For example:



window.onload = function() {
  document.getElementById("mySubmit").disabled = false;

  //or maybe
  document.forms[0].disabled = false;
}

      

+2


source


Use jQuery to create submit button on DOM load

$(document).ready(function() {
    $("form").append("<input type='submit' name='submit' value='submit'>");
}

      

However, this will create a javascript dependency for your application.

Or another option is to put the following code

<form action="post.php" method="post" onsubmit="return false">

      

0


source


Check out this blog post for how to check for DOM readiness. Then create a function that returns true when the DOM is ready and use this function inside your form tag:

<form onsubmit="return my_DOM_ready_function()">

      

0


source







All Articles