0

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?

2
  • 1
    First of all, your script requires jQuery libraries, which in html must be included before your scipt, secondary I prefer to work with $(document).ready(function(){ /* code */ }); instead of $(window).load(); Commented Oct 13, 2013 at 22:44
  • $(window).load(function() {} will not run only when rendering the whole page? Commented Oct 13, 2013 at 22:52

3 Answers 3

2

You should initialize jQuery like this instead:

$(document).ready(function() {
    $( "#target" ).submit(function( event ) {
        alert( "Handler for .submit() called." );
        event.preventDefault();
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Could you please provide a fiddle for troubleshooting?
Glad your sorted it out :)
2

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

My mistake was to close the function, missed a });. And I was trying to solve for hours. --'
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.