views:

48

answers:

2

Hi, i have a form like:

<form id='new_key' action='/foo/bar' method='post'>
 <input type="text" id="u">
 <input type="submit" value="submit">
</form>

I can bind a jquery event to this element like:

<script type="text/javascript">
$('#new_key').ready(function() {
 alert('Handler for .submit() called.');
 return false;
});

It works as expected

but if i do:

<script type="text/javascript">
$('#new_key').submit(function() {
  alert('Handler for .submit() called.');
  return false;
});

it dont work. does anybody knows why? what am i missing?

+4  A: 

You need to do:

$(function() { //equal to $(document).ready() {
  $('#new_key').submit(function() {
    alert('Handler for .submit() called.');
    return false;
  });
});

The form may not be ready to be bound to when you're calling, so you need to wrap it to execute and rig up the handler when the document is ready.

Nick Craver
+1, but why use $(function(){}) instead of $(document).ready()? The first does not read well, while the second is much more clear (IMHO)
Matt
@Matt - Just my habit for brevity since I type it probably 50 times a day I suppose, whichever you prefer will work just fine though...whatever floats your boat.
Nick Craver
@Matt they are actually different, if I'm not mistaken, but slightly, and I can't remember how. I think, though, that $(function(){}) is somehow better.
ocdcoder
@Matt http://groups.google.com/group/jquery-en/browse_thread/thread/ecaebf42a4fb3fae?pli=1
ocdcoder
A: 

$.ready(), if used, ought to be used on the document to indicate the DOM has been fully-loaded.

$(document).ready(function(){

  $("#new_key").submit(function(e){
   e.preventDefault();
   alert("Submit called!");
  });

});​

Online Demo: http://jsbin.com/ojaqo3/edit

Jonathan Sampson