Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

JavaScript で生成したフォームのサイズが小さい

次のように、 select タグの内容を JavaScript で生成した場合、 IE では二つ目のプルダウンの横幅が本来のサイズより小さくなってしまう。 OperaFirefox なら大丈夫。
以下のソース、 FirefoxJavaScript コンソールにはいろいろ言われるけれど気にしない方針で。

<html>
<head>
<script type="text/javascript">
<!--
  var authors = new Array("山田芳裕", "井上雄彦", "戸田誠二");

  var titles = new Array();
  titles[authors[0]] = ["デカスロン", "へうげもの", "度胸星"];
  titles[authors[1]] = ["スラムダンク", "バガボンド", "リアル", "カメレオンジェイル"];
  titles[authors[2]] = ["生きるススメ", "しあわせ", "唄う骨", "化けの皮"];

  function changeAuthor(selform) {
    var author = selform.options[selform.selectedIndex].text;
    if (author) {
      document.all.title.options.length = titles[author].length;
      for (var i=0; i<titles[author].length; i++) {
        document.all.title.options[i].text = titles[author][i];
      }
    }
  }

  function makeOptions() {
    for (var i=0; i<authors.length; i++) {
      option = document.createElement("option");
      option.innerHTML = authors[i];
      document.all.author.appendChild(option);
    }

    for (var i=0; i<authors.length; i++) {
      option = document.createElement("option");
      option.innerHTML = titles[authors[0]][i];
      document.all.title.appendChild(option);
    }
  }

// -->
</script>
</head>
<body onLoad="makeOptions()">
  <select name="author" onChange="changeAuthor(this)">
  </select>
  <select name="title">
  </select>
</body>
</html>

次のようにすれば症状は改善される。

  • 山田芳裕」を「井上雄彦」にして、もう一回「山田芳裕」に戻す
  • 一つ目の select と二つ目の select の間に br とか hr とかを入れて、二つ目の select が行頭 (?) にくるようにする
  • select に style="width:15ex" とか指定する