I’m trying to pass an optional argument to a javascript function from jQuery. In the below example the function receiving the argument is ‘foo’. It works fine with the second bit of jQuery which passes the argument. The first bit of jQuery doesn’t have any arguments that I pass in, but jQuery still seems to pass an object.
Ultimately I want ‘bar’ to be an optional parameter, and set to 0 if I don’t pass anything in.
//jQuery Bit #1
$('#id').change(foo);
//jQuery Bit #2
$('#id2').click(function(e){
var bar = $(e.target).text();
foo(bar);
});
function foo(bar) {
if (!bar) var bar = 0;
//do stuff here
}
Since jQuery is passing in an object should I just pass ‘bar’ in as an object and check for it as an attribute of the object? Or am I missing something that jQuery does or that I should be doing with jQuery in this situation?
Here jQuery is passing the event object into the
clickcall back which is by design. If you want to have the jQuery invoke the callback without an argument then you need to wrap it in a lambda and explicitly not pass an argument