Rob
Rob

Reputation: 3

How do I bind an event handler to the "change" JavaScript event, or trigger that event on an element?

I do not understand how to get change event to call a function.

$(function () {

  function foo() {
    alert("ok");
  }

  //works
  $('#myElement').change(function() {
    alert("ok");
  });

  //does not work
  $('#myElement').change(foo);

  //does not work
  $('#myElement').change(foo());
}

Upvotes: 0

Views: 198

Answers (5)

tenkod
tenkod

Reputation: 297

This should work:

$('#myElement').change(foo);

In your code example you are missing one closing bracket.

Upvotes: 0

gion_13
gion_13

Reputation: 41533

to bind a function to the change event :
$('#id').bind('change',function(){/*code here*/});
and to trigger the event :
$('#id').trigger('change');

Upvotes: 0

Kalyan
Kalyan

Reputation: 498

versions 1 and 2 work for me on FF3.6 and IE7. version 3 executes right away because of the presence of the parenthesis. Can you give the browser on which version 2 is not working.

Upvotes: 0

Jacob Relkin
Jacob Relkin

Reputation: 163238

All of the following examples should work, if not then you are doing something wrong.

$(function() {
   function foo(e) {
     alert("ok");
   }
   $('#myElement').change(function(e) {
     alert("ok");
   });
   $('#myElement').change(foo);

   //trigger the event like so:
   $('#myElement').change();
});

Upvotes: 2

Satyajit
Satyajit

Reputation: 3859

$('#myElement').change(function() {
    foo();
  });

Upvotes: 0

Related Questions