views:

97

answers:

4
$(document).ready(SetupButtonClicks());

function SetupButtonClicks() {
    $('#btnJavaPHP').click(DoPHPStuff());
}

function DoPHPStuff() {
    //stuff
}

I have this code in my javascript file, when I debug it I see it call SetupButtonClicks() like it should but after that is done it calls DoPHPStuff(). DoPHPStuff() should only be called when btnJavaPHP is clicked. What am I doing wrong?

+3  A: 

Remove the ().

By writing $(document).ready(SetupButtonClicks()), you are calling SetupButtonClicks and passing its return value to ready.
Similarly, by writing $('#btnJavaPHP').click(DoPHPStuff()), you are calling DoPHPStuff (immediately) and passing whatever it returns to click().

You need to pass the functions themselves by writing $(document).ready(SetupButtonClicks) and $('#btnJavaPHP').click(DoPHPStuff).

SLaks
+11  A: 

Change your SetupButtonClicks function:

$('#btnJavaPHP').click(DoHPStuff);

The way you've got it coded, you're telling Javascript to call the function, not to use it as the "click" handler. The parenthesis are an operator that causes a function to be called.

Pointy
Thanks, that fixed it.
jamone
@jamone you're $(document).ready is probably still wrong... make sure to change that too.
galambalazs
@galambalazs yeah, I fixed the $(document).ready line at the same time. Thanks
jamone
+2  A: 
function DoPHPStuff() {
    //stuff
}

function SetupButtonClicks() {
    $('#btnJavaPHP').click(DoPHPStuff);
}

$(document).ready(SetupButtonClicks);    
galambalazs
+1  A: 

With the exception of a function declaration, a pair of parentheses following a function's identifier causes the function to execute. Examples:

// function declaration; function not executed
function SetupButtonClicks() {

}

// function executed
SetupButtonClicks();

// function not executed
SetupButtonClicks;
Jeremy