I have this jquery script, and it does not work in head tag.
<script type="text/javascript">
$(window).load(function() {
$( "#target" ).submit(function( event ) {
alert( "Handler for .submit() called." );
event.preventDefault();
});
}
</script>
But if I put the code below the form it usually works.
I want to put it in a .js file. But does not work in the head tag, only if I include after the form.
It is possible to make this code work in head tag?
3 Answers 3
You should initialize jQuery like this instead:
$(document).ready(function() {
$( "#target" ).submit(function( event ) {
alert( "Handler for .submit() called." );
event.preventDefault();
});
});
2 Comments
Probably the form is not rendered before .load event is fired.
Check what window is, but you might want to write:
<script type="text/javascript">
$(document).ready(function() {
$( "#target" ).submit(function( event ) {
alert( "Handler for .submit() called." );
event.preventDefault();
});
});
</script>
Check this link
If you don't use the .ready approach, it is going to execute the code, search for #target and find nothing, because the render has not passed the object that you are targeting so it is not able to find it
1 Comment
});. And I was trying to solve for hours. --'Try this?
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on("submit", "#target", function(event) {
alert("Handler for .submit() called.");
event.preventDefault();
});
});
</script>
$(document).ready(function(){ /* code */ });instead of$(window).load();$(window).load(function() {}will not run only when rendering the whole page?