tags:

views:

29

answers:

3

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?

+1  A: 

Try wrapping your code in a $(function() { }) block:

$(function() {
  $('#new_key').submit(function() {
    alert('Handler for .submit() called.');
    return false;
  });
});
strager
i surround it by a function but then i must bind this function with a event right? maybe the $(document).ready ?
VP
`$(function() { X; });` is equivalent to `$(document).ready(function() { X; });`.
strager
+5  A: 

Your form tag ID should just be declared as new_key, not #new_key:

<form id='new_key' action='/foo/bar' method='post'>

The # is not part of the ID, it's a signal to jQuery to match an element by it's ID, based on #'s usage in CSS.

Tobias Cohen
i was sleeping. the new id in the form declaration dont have it. it was a mistake
VP
+2  A: 

$.fn.ready executes when the DOM is ready. It doesn't look at the jQuery object. So, your '#new_key' part is being ignored.

As Tobias Cohen answered, the ID of your form element needs to be changed by removing the preceding #.

strager
i was sleeping. the new id in the form declaration dont have it. it was a mistake
VP