I created some JavaScript code that submits the form out the <form> tag. Here is the code:
<script type="text/javascript">
var myForm = document.forms['myForm'];
var formSubmit = document.getElementById('formSubmit');
formSubmit.onclick = function(){
myForm.submit();
}
</script>
<form name="myForm" action="http://msn.com" method="post">
</form>
<div id="formSubmit"><button>Click me</button></div>
When I try this code on http://jsfiddle.net/HrCxz/ it works fine. But When I add this code in an HTML file and run the page, it doesn’t work. What’s wrong with the code? Please help me fix this.
In the fiddle your code is run inside an
onloadhandler. This is the default option, but the left-hand panel allows you to change it. If you change it to run in the<head>then the fiddle doesn’t work either: http://jsfiddle.net/HrCxz/1/You need to either add an
onloadhandler of your own, or move your script block to after the elements it tries to manipulate. Script blocks are executed in the order they’re found as the browser parses the page top to bottom. JS in any given script block can only manipulate elements that have already been parsed, i.e., ones that appear closer to the beginning of the source, unless you put your code in an event handler called from theonloadevent (or from document ready for browsers that support it or if you use a library that provides it or otherwise code it yourself).