Deckard
Deckard

Reputation: 1433

Why is my function called two times?

    $(document).ready(function () {
 doSomething(1);    
 $('#pp').click( doSomething(2) );//why is this called?? I didn't click the button..
});

function doSomething(v) {
 alert(v);
}
</script>

<body>

<input type="button" id="pp" value="asdf" />

I need a function to be called on load and click. But somehow doSomething() is called two times on load. What's going on..??

Upvotes: 0

Views: 205

Answers (4)

Kranu
Kranu

Reputation: 2567

Change the ready fragment to

$(document).ready(function() {
  doSomething(1);
  $('#pp').click(function() {
    doSomething(2);
  });
});

Upvotes: 2

rgroli
rgroli

Reputation: 1379

I think there's an error in your event-binding. It should be:

$('#pp').bind('click', function () { doSomething(2); });

Upvotes: 0

Amber
Amber

Reputation: 526613

You need to wrap what you pass to .click() in a function {}. Otherwise it executes when the .click() line executes and the result is passed to .click().

Upvotes: 0

Francisco
Francisco

Reputation: 4101

$(document).ready(function () {
 doSomething(1);    
 $('#pp').click( function(){doSomething(2);} );
});

Upvotes: 0

Related Questions