开发者

IE6 and 7 can't detect dynamically added checkboxes in javascript

开发者 https://www.devze.com 2023-03-20 23:42 出处:网络
I have something like this in my AJAX application: <html> <head> <script type=\"text/javascript\">

I have something like this in my AJAX application:

      <html>
<head>
    <script type="text/javascript">
        var counter=4;
        function newcheckbox() {
            var newrow=document.getElementById('tabl').insertRow(0);
            var cell1=newrow.insertCell(0);
            var n=document.createElement("input");
            n.type="checkbox";
            n.name="item";
            cell1.appendChild(n);
            var cell2=newrow.insertCell(1);
            cell2.innerHTML=counter;
            counter++;
        }
        function listlength() {
            alert(document.list.item.length);
        }
    </script>
</head>
<body>
    <button onclick="newcheckbox();">new checkbox</button>
    <button onclick="listlength();">alert checkbox list length</button>
    <form name="list">
    <table id="tabl">
        <tr>
            <td><input type="checkbox" name="item"/></td><td>3</td>
        </tr>
        <tr>
            <td><input type="checkbox" name="item"/></td><td>2</td>
        </tr>
        <tr>
            <td><input type="checkbox" name="item"/></td><td>1</td>
        </tr>
    </form>开发者_如何学Go;
</body>
      </html>

As you can see, if new checkbox button is clicked, as new checkbox is added. There is another button which alerts the length of the checkbox list. In Firefox, you get an updated length of the list, but in IE 6 and 7 it says the length is still 3. How do you get around this problem in IE?


IE won't let you set the "name" attribute after the element is created:

var n=document.createElement("<input name='item'>");

If you do it that way, however, it should work.

edit — looks like Firefox (since FF4, and apparently never in standards mode) doesn't like doing that, so you'll have to do some browser sniffing or feature testing to know whether it works to create an element with a name like that.


In those version of IE to create an input element, you have to do something like this:

document.createElement('<input type="checkbox" name="foo" />');
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号