Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .click not working

We have a problem in IE with some users where the onclick event isn't working:

<button type="button" id="btnSomething" name="btnSomething" onClick="myFunction();">Continue</button>

After digging around the net, people suggested using jQuery's .click event for cross browser compatibility.

So I've tried the following:

<script type="text/javascript">$('#btnSomething').click(function(){myFunction();});</script>

This doesn't work, I've tried adding in alert('test'); but that doesnt get called either. If it makes any difference, I didnt remove the onClick="myFunction();" from the button element, just adding the above JS directly after the button in the HTML file.

like image 806
Igor K Avatar asked Sep 03 '26 22:09

Igor K


2 Answers

Two points here. First, you should only bind your event handlers when the DOM is complete. jQuery facilitates this for you: you should always put all your jQuery code in the document.ready handler:

$(document).ready(function(){
    $('#btnSomething').click(function(){
        around ();
    });
});

Second, because your function already has a name (around), you don't need to add the extra anonymous function; you can call it like this:

$(document).ready(function(){
    $('#btnSomething').click(around);
});
like image 114
lonesomeday Avatar answered Sep 05 '26 14:09

lonesomeday


As others have said you need it inside a document.ready handler, but it can be much shorter, like this:

<script type="text/javascript">
  $(function(){ 
    $('#btnSomething').click(around);
  });
</script>

If you don't have it inside a ready handler, the $('#btnSomething') may not find the element, as it won't be in the DOM to find yet.

like image 37
Nick Craver Avatar answered Sep 05 '26 14:09

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!