how can I give an array as options to select element?

后端 未结 5 1570
南笙
南笙 2020-12-08 15:43

I have a select element on my HTML page. I want to populate it with an array. as we can give an array as dataprovider to comboBox in action script. I do the following

<
5条回答
  •  一整个雨季
    2020-12-08 16:11

    I highly recommend you use a format like the following:

    var options =
    [
      {
        "text"  : "Option 1",
        "value" : "Value 1"
      },
      {
        "text"     : "Option 2",
        "value"    : "Value 2",
        "selected" : true
      },
      {
        "text"  : "Option 3",
        "value" : "Value 3"
      }
    ];
    
    var selectBox = document.getElementById('rec_mode');
    
    for(var i = 0, l = options.length; i < l; i++){
      var option = options[i];
      selectBox.options.add( new Option(option.text, option.value, option.selected) );
    }
    

    You don't run in to the problem of having to select a default option and you can easily generate the options array dynamically.

    -- UPDATE --

    ES6 version of the above code:

    let optionList = document.getElementById('rec_mode').options;
    let options = [
      {
        text: 'Option 1',
        value: 'Value 1'
      },
      {
        text: 'Option 2',
        value: 'Value 2',
        selected: true
      },
      {
        text: 'Option 3',
        value: 'Value 3'
      }
    ];
    
    options.forEach(option =>
      optionList.add(
        new Option(option.text, option.value, option.selected)
      )
    );
    

提交回复
热议问题