Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: getElementById problem in IE

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

like image 725
Gaurav Sharma Avatar asked Sep 14 '10 11:09

Gaurav Sharma


2 Answers

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.

like image 129
Magnar Avatar answered Nov 10 '22 19:11

Magnar


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.

like image 1
Ben Avatar answered Nov 10 '22 19:11

Ben