Gaurav Sharma
Gaurav Sharma

Reputation: 4052

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

Upvotes: 9

Views: 22151

Answers (3)

parth joshi
parth joshi

Reputation: 157

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.

Upvotes: -1

Ben
Ben

Reputation: 1485

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.

Upvotes: 1

Magnar
Magnar

Reputation: 28830

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.

Upvotes: 13

Related Questions