Skip to content
Advertisement

Capturing jQuery form submit event

I don’t know what is wrong with that, because I was following at every step the tutorial from jquery.com regarding the form submit event.

My Javascript:

[Ofc. latest jQuery library is included].

<script type="text/javascript">
$("form#addFav").submit(function(event) { event.preventDefault(); alert("hello"); });
</script>

Have also tried with the $(document).ready() event:

$(document).ready(function(){
$("form#addFav").submit(function(event) { event.preventDefault(); alert("hello"); });
});

Here is my HTML form code:

<form action="" id="addFav">
     <input type="text" name="name" class="thin-d"/>
     <input type="submit" value="Send"/>
</form>

So, regarding the above Javascript code, it is supposed to work (I mean it should prevent default action [submitting form] and send the alert then), but it all doesn’t work – have tried with thousands of combinations, but I fail’d. So I’m waiting for your solutions. I’d appreciate every one.

Advertisement

Answer

You probably have some syntax error or somthing like that somewhere else, because what you have just works.

Are you sure there aren’t any JS errors?

P.S. I would alwyas go for the latter code to ensure that the elements are in the DOM before trying to attach events.

Advertisement