Click function firing on pageload?
Asked Answered
L

2

9

Trying to figure out how this is possible...

$(function() {
   $('#saveBtn').click(save());
});

function save(){
    alert('uh');
}

.

<form id="video-details" method="post" action="">
    <input id="saveBtn" class="submit" type="submit" name="submit" value="Submit Video" disabled/>
</form>

I set a breakpoint on the save() function and it is being called by an anonymous function on the line with the click event listed. However this is happening directly on load, not to mention that the input starts off invisible and disabled so there is no way to click it.

I changed the click function to different elements that both exist and don't exist and whatever I make it the function still fires on pageload.

Not sure where else to investigate the cause of this, but I'm assuming it's not normal behaviour

Libido answered 5/9, 2011 at 20:42 Comment(0)
L
30

Try changing your script to:

$(function() {
   $('#saveBtn').click(save);
});

function save(){
    alert('uh');
}

By having brackets in the click declaration you are calling the function. If you just use the function name then you are providing a reference to the function instead of a call.

Calling with variable

If you are calling the function with a variable you would need to make use of a closure (assuming that you have access to the variable when declaring the event

$(function(){
  var foo = 'bar';
  $('#saveBtn').click(
    function(){
      save(foo);
    });

function save(message){
  alert(message);
}

For more information on closures check out How do JavaScript closures work?.

Leisured answered 5/9, 2011 at 20:44 Comment(3)
wow good to know. i thought () was required to separate function from variable!Libido
what if the function call needed arguments, say save(this).. would that call it as well?Libido
@Libido - I've updated my answer for calling with an argument. The this keyword would refer to the calling context (element that was clicked), don't know if you were just using that as an example argument name.Leisured
N
1

try changing to this. You are invoking click accidentally

$(function() {
   $('#saveBtn').click(function (){
     save()});
});
Neap answered 5/9, 2011 at 20:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.