codingsplash
codingsplash

Reputation: 5045

jQuery binding : function runs before the event

I am trying to understand event binding in jQuery. I have written a simple code as follows:

<html>

<script language="javascript" src="jquery.js"></script>

<body>
<form>
<input type="button" name="bu1" value="click me">
</form>
</body>

<script language="javascript">
jQuery("input[type='button']").bind('click',alert('Hello'));
</script>


</html>

When I run the page, the alert happens on load rather than when I click the button. Can anyone help me to understand where is it I am going wrong?

Upvotes: 0

Views: 1464

Answers (4)

robertp
robertp

Reputation: 3642

Yeah, wrap it up in a function, I also would add the event.preventDefault() as well:

jQuery("input[type='button']").bind('click', function(e) { 
  e.preventDefault();        
  alert('Hello');
});

Rob

Upvotes: 0

sujal
sujal

Reputation: 1050

<script language="javascript">
 jQuery(function(){
      jQuery("input[type='button']").bind('click',function(){
      alert('Hello')
   })
 })

</script>

Do inside

Jquery(function(){

})

and edit

 jQuery("input[type='button']").bind('click',function(){
          alert('Hello')
       })

Upvotes: 0

archil
archil

Reputation: 39491

You should pass function as a second argument

jQuery("input[type='button']").bind('click', function() {
    alert('Hello')
});

Otherwise, javascript runs alert('Hello') to get value for second parameter of bind function, so you get alert displayed in your window.

Upvotes: 0

Rafael
Rafael

Reputation: 18522

jQuery("input[type='button']").bind('click', function () {
    alert('Hello');
});

You need to pass a function, not call it. So in the code above I have added an anonymous function which calls alert.

Upvotes: 3

Related Questions