Hardeep Brah
Hardeep Brah

Reputation: 17

Jquery .submit not working on chrome

I am working on ajax.
Browser is google chrome.
Instead of alerting ok when i click on submit, my browser submits the form. What's wrong here?

    <html>
    <head>
    <script type="text/javascript" src="/cp/scripts/jquery-1.7.2.js"></script>
    <script language="javascript">
    $("#test").submit(function(){
    //$.post("test.php", this.serialize());
    alert('ok');
    return false;
    });
    </script>
    </head>
    <body>
    <form id="test">
    <input type="text" name="name">
    <input type="submit">
    </form>
    </body>
    </html>

Upvotes: 0

Views: 4167

Answers (2)

Justin Morgan
Justin Morgan

Reputation: 30715

First, make sure the function is being executed on document.ready, and then don't forget to prevent the default behavior for the submit event:

$(document).ready(function() {
    $("#test").submit(function(evt){
        evt.preventDefault();
        alert('ok');
        return false;
    });
});

Tested on jsFiddle in Chrome.

Upvotes: 1

Rob W
Rob W

Reputation: 348992

The form is not defined yet when the script is executed. Wrap it in a $().ready event:

$(document).ready(function() {
    $("#test").submit(function() {
    //$.post("test.php", this.serialize());
    alert('ok');
    return false;
    });
});

I can see the following question coming: "What not defined?".
Yes:

...
# Hey, a script tag, let's wait, and load the resource.
<script type="text/javascript" src="/cp/scripts/jquery-1.7.2.js"></script>

# Hey a script tag!
<script language="javascript">
$("#test").submit(function(){
//$.post("test.php", this.serialize());
alert('ok');
return false;
});
</script>
# The script block has ended, let's parse the script
# ... *calls* $('#test'). ....

# Now, #test is defined. Too late...
<form id="test">
# ...

Upvotes: 8

Related Questions