How to prevent form submiting before DOM is ready?
I'm using javascript to validate the form,
but can't 开发者_如何转开发handle the case when the form is submitted before DOM is ready
I tried :
<form method="POST" disabled="disabled">
<input type="submit" />
</form>
But the form can still be submited.
Just a check before submit just to prevent a post before Dom 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>
One braindead way would be to keep the submit button (or form) disabled and enable it within the window
or the body
's onload
event. E.g:
window.onload = function() {
document.getElementById("mySubmit").disabled = false;
//or maybe
document.forms[0].disabled = false;
}
Use jQuery to create the submit button on DOM load
$(document).ready(function() {
$("form").append("<input type='submit' name='submit' value='submit'>");
}
This will however create a dependency on javascript for your application
Or another option is to place the following code
<form action="post.php" method="post" onsubmit="return false">
Check this blog entry, it describes how to check for DOM readiness. Then, create a function which returns true when DOM is ready and use this function inside your form tag:
<form onsubmit="return my_DOM_ready_function()">
精彩评论