Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery event handler not working

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?

like image 752
VP. Avatar asked Mar 05 '10 21:03

VP.


2 Answers

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.

like image 62
Nick Craver Avatar answered Oct 25 '22 05:10

Nick Craver


$.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

like image 31
Sampson Avatar answered Oct 25 '22 04:10

Sampson