views:

52

answers:

5

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.

A: 

If the button is contained within a form, make sure you return false in the click function to prevent the form from submitting.

Gene
Thanks I will however this is not a submit button, type is button, not submit.
Igor K
A: 

igor,

you'll need to reference the jquery lib and then do something like this:

<script src= "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>

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

also, remove the onclick section from your button - unobtrussive javascript. hope it works..

jim
jQuery is already used in the app and is on the page. Made a mistake in writing "around ()", should have been "myFunction()", exactly the same as the onClick event. I've tried it like this and it didn't work.
Igor K
A: 

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);
});
lonesomeday
Im outputting the SCRIPT block directly after the HTML is output dynamically using Response.Write. I'll try .ready however had thought this wasn't required.
Igor K
Tried this although it doesn't work.
Igor K
In that case, there is a problem somewhere else in your code. Could you give us a link to it, or upload it to jsFiddle/jsBin?
lonesomeday
A: 

it works fine. make sure to run your jQuery code in a domready block. see here: http://jsbin.com/inubo4

Moin Zaman
That doesn't work in our app for some reason.
Igor K
A: 

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.

Nick Craver