-4

Summary: I would like to call an external function upon a status change for a checkbox.

The following code which includes the function to call upon the change works (code available at JSFiddle, commented section)

HTML

<input type="checkbox" id="cb">

JS

$("#cb").change(function () {
        if ($("#cb").prop('checked'))
        {
            alert('checked');
        } else {
            alert('unchecked')
        }
    });

As expected, an alert is raised when checking or unchecking the checkbox.


I now want to move the function part outside the .change() method:

$("#cb").change(alertme());

function alertme () {
        if ($("#cb").prop('checked'))
        {
            alert('checked');
        } else {
            alert('unchecked')
        }
    }

This does not work anymore (no alert on status change). Why is it so?

WoJ
  • 27,165
  • 48
  • 180
  • 345
  • `alertme` instead of `alertme()` – Jeff Dec 21 '15 at 14:40
  • The answers are clear, thanks. The downvotes, well, ... – WoJ Dec 21 '15 at 14:42
  • You have two ways: first: `$("#cb").change(alertme);` Second: `$("#cb").change(function() { alertme(); });` I prefer second version, you need to pass reference of function as you can see or reproduce a function – Davide Dec 21 '15 at 14:43

3 Answers3

6

You just need the function definition, don't execute it:

$("#cb").change(alertme);
Curtis
  • 101,612
  • 66
  • 270
  • 352
2

Don't execute the function, just pass it as a callback:

$("#cb").change(alertme);

function alertme () {
        if ($("#cb").prop('checked'))
        {
            alert('checked');
        } else {
            alert('unchecked')
        }
    }
onerror
  • 606
  • 5
  • 20
1

You want to just pass the function name to the change event, not actually call the function and pass the return value. Use this instead:

$("#cb").change(alertme);
jeffjenx
  • 17,041
  • 6
  • 57
  • 99