9

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...)

Gaurav Sharma
  • 4,032
  • 14
  • 46
  • 72
  • Related: [Do DOM tree elements with IDs become global properties?](/q/3434278/4642212). This is a possible explanation of what’s going on. Named elements and elements with IDs become global properties. Old IE very likely simply retrieves that global property instead of verifying that this ID actually exists, etc. – Sebastian Simon Feb 08 '22 at 15:29

3 Answers3

13

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
  • 28,550
  • 8
  • 60
  • 65
  • 1
    @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 Sep 14 '10 at 11:37
1

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
  • 1,435
  • 3
  • 10
  • 10
-1

I agree, IE is poor in understanding things at html level. I would rather add the link to button rather than using anchor elements, as IE is having trouble at anchor level with document.getElementById(). Try same at button and will work for other users.

James A Mohler
  • 11,060
  • 15
  • 46
  • 72
parth joshi
  • 157
  • 1
  • 4
  • 13