views:

66

answers:

2

I am trying to attach a click event to a check box using JavaScript. Shown below is the HTML and JS.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <input type="hidden" name="caution_c" value="0">
        <input type="checkbox" id="caution_c" name="caution_c" value="1" tabindex="120">
        <script type="text/javascript">
            var cb = document.getElementById('caution_c');
            cb.onclick = function() {
                alert(1);
            }
        </script>
    </body>
</html>

The problem is that in IE, the click event does not fire. I have narrowed down the problem location. The issue is that there is a hidden input just before the check box and both these elements have the same name. I'm not sure why this is causing a problem(after all, I'm using getElementById and the hidden element does not even have an id).

Is there a valid reason for this type of behavior (IE only. Works fine in Firefox...as always :( )? Also, is there a good workaround (I could just do document.getElementsByName('caution_c')[1] but I don't want to...)

+7  A: 

Internet Explorer gets confused over name and id - it is highly recommended to treat these two attributes as if they were the same.

You can fix it either by 1) ensure that there are no id/name conflicts in your document, or 2) override IE's native getElementById-method.

Read more about it here.

Magnar
wow...that's just insane!!!!
Gaurav
@Guarav: Welcome to IE.
annakata
@Guarav - insane? Yep. That's IE for you. Why do you think so many web developers hate microsoft so intensely. This glitch is just the tip of the iceberg. :( Hopefully the new IE version 9 will improve things, but it won't save us all from having to support all those crumbly old versions of IE.
Spudley
+1  A: 

Try using a different event such as onchange or onfocus to see if that solves it. Also I don't think onclick will be fired if a user tabs onto the checkbox, which may or not be how you intend it to work.

Ben