「JavaScript入門」Optionオブジェクトの使い方

書式
var optionElementReference = new Option(text, value, defaultSelected, selected);

プロパティ
text テキスト
value: 属性の値
defaultSelected :ディフォルト選択
selected:現在選択されるか

サンプルコード

var city = document.getElementById('city');
var options = [ '東京', '大阪', '福岡' ];

options.forEach(function(element, key) {
  if (element == '東京') {
    city[city.options.length] = new Option(element, city.options.length, false, false);
  }                
  if (element == '大阪') {
    city[city.options.length] = new Option(element, city.options.length, true, false); 
  }
  if (element == '福岡') {
    city[city.options.length] = new Option(element, city.options.length, false, true); 
  }
});

実行結果

<select id="city">
  <option value="0">東京</option>
  <option value="1" selected="">大阪</option>
  <option value="2">福岡</option>
</select>

 

JavaScript

Posted by arkgame