Reputation: 8792
I have something like the following..
$(document).ready(function() {
$('#doReport').click(doReport);
});
function doReport(type) {
if (type === undefined) {
type = 'blah';
}
alert (type);
}
If I run doReport()
from the console or standalone in the javascript with nothing in it, it will return 'blah' (as expected), and obviously if I call doReport('wibble');
it returns 'wibble' as you would expect.
But if I run it by clicking the element with ID doReport (utilising the bind I set up in .ready) it returns [object Object]
I don't understand why that would be the case.
Upvotes: 2
Views: 116
Reputation: 413915
The jQuery library passes your event handlers an "event" object. It will always be there. It's a "wrapped" or "fixed" version of the native browser object, making it somewhat easier to deal with.
Here is the documentation for such objects.
Also of note is the fact that jQuery will invoke your handler functions such that this
refers to the DOM element for which the handler is being invoked.
Also also, as @Ericson578 points out in a good comment, jQuery allows additional parameters to be set up, which means that your handler may be passed additional parameters. That might be useful if you've got a single event handler function to be bound to different elements, but you'd like to qualify its behavior with some different flags or whatever based on the particulars of an element.
Upvotes: 7
Reputation: 29831
wrap it with another function if you need to pass an argument to your function.
$(document).ready(function() {
$('#doReport').click(function(event){
doReport('blah');
});
});
Upvotes: 0
Reputation: 8942
From JQuery - .click()
.click( handler(eventObject) ) handler(eventObject)A function to execute each time the event is triggered.
Your doReport()
function is getting an event object.
Upvotes: 0
Reputation: 82933
When jQuery calls the function passed as parameter to click, it passed event object as the argument hence you are getting the alert as [object Object]. Check this:
Upvotes: 0
Reputation: 237995
This is because event handlers are triggered with an object (specifically, the event
object) passed as the first argument.
This is the reason you see such syntax as
$('#doReport').click(function(e) {
If you want to call your function without any parameters, you'll need to create a wrapping function to do so:
$(document).ready(function() {
$('#doReport').click(function() {
doReport();
});
});
Upvotes: 1