views:

847

answers:

2

I have a table in my web site, with a select element in one of the cells. If I try to change the content of the element, everything works fine in most of the browsers that I've tried (including IE6, surprisingly enough), but in IE7, the table cell does not adjust its width to fit the select element. Is there any way to make the table cell resize itself properly?

You can see the problem for yourself with this simple test:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
<html><head>
<title>Table cell width test</title>
</head>
<body>
<table>
    <tr>
        <td style="border: solid black 1px">
            <select id="test">
            </select>
        </td>
    </tr>
</table>
<script type="text/javascript">
window.onload = function() {
    var option = document.createElement("option");
    option.innerHTML = "asdfasdfasdfasdfasdfasdfasdfasdf";
    document.getElementById("test").appendChild(option);
};
</script>
</body></html>
+1  A: 

Yeah, this is a shitty problem of IE's referred to as "hasLayout". To understand the problem, this is a great article: http://www.satzansatz.de/cssd/onhavinglayout.html

To solve your problem, you just have to force the cell and its content to recalculate its layout. A simple way to do it is to just append and remove an empty div:

<script type="text/javascript">
window.onload = function() {
    var test = document.getElementById('test');
    var option = document.createElement("option");
    option.innerHTML = "asdfasdfasdfasdfasdfasdfasdfasdf";
    test.appendChild(option)

    var div = document.createElement("div");
    test.parentNode.appendChild(div);
    test.parentNode.removeChild(div);
}
</script>

Shitty... but it works.

Cheers

Marcus Westin
I tried it and it didn't work. I would experiment with it, but I tried petersendidit's solution and it was good enough for me.
mikez302
+1  A: 

Looks like you can also change the display to none and then back to inline, one right after the other, and it will fix the problem to, doesn't seem to cause a flicker either.

jQuery.fn.ie7fix = function(){
    if (!($.browser.msie && $.browser.version == "7.0")) return $(this);
    return $(this).hide().show();
};
$('#test').append('<option>asdfasdfasdfasdfasdfasdfasdfasdf</option>').ie7fix();
PetersenDidIt
mikez302
I tried your solution, with my fix to the condition, and it worked! Thank you.
mikez302
You are correct about the if statement, corrected it. Glad it worked
PetersenDidIt