向多个Select元素添加选项

时间:2022-06-24 21:26:59

I have an HTML page, including a Form with multiple <select> elements. I know how to load the elements into a single <select>; here’s a piece of the code that works as I expect it to:

我有一个HTML页面,包括一个带有多个中;这是一段代码,可以按照我的预期运行:

$(function() {
    google.script.run.withSuccessHandler(buildProjectList)
    .getProjects();
  });

  function buildProjectList(options) {
    var list = $('#projectList');
    list.empty();
    for (var i=0; i<options.length; i++) {
      list.append('<option value="' + options[i] + '">' + options[i] + '</option>');
    }
  }

It correctly gets a list of Projects, and adds the Options to the <select>.

它正确获取项目列表,并将选项添加到

Now what I am trying to do is add a list of options (all the same) to multiple <select> elements.

现在我要做的是向多个

Here’s the code as I’ve written it:

这是我编写的代码:

$(function() {
    google.script.run.withSuccessHandler(buildDropDowns)
    .getDropDowns();
  });

function buildDropDowns(sizes) {
    var selections = document.getElementsByClassName('resourceSize');
    for(var i=0; i<selections.length; i++) {
      console.log(selection);
      for(var j= 0; j<sizes.length; j++) {
        selections[i].options.add(sizes[j], sizes[j]);
      }
    }
  }

function buildDropDowns(sizes) {
    var selections = document.getElementsByClassName('resourceSize');
    for(var i=0; i<selections.length; i++) {
      var selection = selections[i];
      console.log(selection);
      for(var j= 0; j<sizes.length; j++) {
        selection.options.add(sizes[j], sizes[j]);
      }
    }
  }

I’ve also tried it where I create a new variable for each element as it iterates through:

我也尝试过,在迭代时为每个元素创建一个新变量:

function buildDropDowns(sizes) {
  var selections = document.getElementsByClassName('resourceSize');
  for(var i=0; i<selections.length; i++) {
    var selection = selections[i];
    console.log(selection);
    for(var j= 0; j<sizes.length; j++) {
      selection.options.add(sizes[j], sizes[j]);
    }
  }
}

In either case, this is the error I’m getting in the console:

无论哪种情况,这都是我在控制台中遇到的错误:

Uncaught TypeError: Failed to execute 'add' on 'HTMLOptionsCollection':
The provided value is not of type '(HTMLOptionElement or HTMLOptGroupElement)'

I’ve tried a couple different things based on some searching I’ve done, but no matter what I try, I’m getting the same error message. I’m assuming it has something to do with the difference between getElementById and getElementsByClassName. One returns the element itself, the other an array of elements. But I would think that I should be able to iterate through that array, and use the add function.

基于我已经完成的一些搜索,我尝试了几个不同的东西,但无论我尝试什么,我都会得到相同的错误信息。我假设它与getElementById和getElementsByClassName之间的区别有关。一个返回元素本身,另一个返回元素数组。但我认为我应该能够遍历该数组,并使用add函数。

I can see that the iteration is working; here is what console.log(selection) shows as it cycles through each element:

我可以看到迭代正在运行;这是console.log(选择)在循环每个元素时显示的内容:

<select id=​"busMerchPlan" name=​"busMerchPlan" class=​"resourceSize">​</select>
<select id=​"busMerchAlloc" name=​"busMerchAlloc" class=​"resourceSize">​</select>​
<select id=​"busMerchBuy" name=​"busMerchBuy" class=​"resourceSize">​</select>​
<select id=​"busMerchPDD" name=​"busMerchPDD" class=​"resourceSize">​</select>

Is there a way to iterate through the elements, and for each element, add each of the Options? Or do I need to use a getElementId statement for each of the elements I want to modify?

有没有办法迭代元素,并为每个元素添加每个选项?或者我是否需要为我想要修改的每个元素使用getElementId语句?

function buildDropDowns(sizes) {
  var list = $('#busMerchPlan');
  list.empty();
  for (var i=0; i<options.length; i++) {
    list.append('<option value="' + options[i] + '">' + options[i] + '</option>');
  }

  var list = $('#busMerchAlloc');
  list.empty();
  for (var i=0; i<options.length; i++) {
    list.append('<option value="' + options[i] + '">' + options[i] + '</option>');
  }

  var list = $('#busMerchBuy');
  list.empty();
  for (var i=0; i<options.length; i++) {
    list.append('<option value="' + options[i] + '">' + options[i] + '</option>');
  }

  var list = $('#busMerchPDD');
  list.empty();
  for (var i=0; i<options.length; i++) {
    list.append('<option value="' + options[i] + '">' + options[i] + '</option>');
  }
}

I can do that, but in the end, I'll have 20+ <select> elements, and there has to be a better way than brute force.

我可以做到这一点,但最后,我将有20多个

3 个解决方案

#1


3  

Uncaught TypeError: Failed to execute 'add' on 'HTMLOptionsCollection': The provided value is not of type '(HTMLOptionElement or HTMLOptGroupElement)'

未捕获的TypeError:无法在'HTMLOptionsCollection'上执行'add':提供的值不是'(HTMLOptionElement或HTMLOptGroupElement)'的类型

The error message suggests you add a value that's either a HTMLOptionElement or a HTMLOptGroupElement. So, you can write a function that creates such an element :

该错误消息建议您添加一个HTMLOptionElement或HTMLOptGroupElement的值。所以,你可以编写一个创建这样一个元素的函数:

function createOption(option, label) {
      var option = document.createElement("option");
      option.setAttribute("value", option);
      option.innerHTML = label;

      return option;
}

And call it in your selections[i].options.add function.

并在您的选择[i] .options.add函数中调用它。

function buildDropDowns(sizes) {
    var selections = document.getElementsByClassName('resourceSize');
    for(var i=0; i<selections.length; i++) {
      //console.log(selection);
      for(var j= 0; j<sizes.length; j++) {
        selections[i].options.add(createOption(sizes[j], sizes[j]));
      }
    }
}

function createOption(option, label) {
  var option = document.createElement("option");
  option.setAttribute("value", option);
  option.innerHTML = label;
  
  return option;
}
  
var sizes = ["XXL", "XL", "L", "M", "S", "XS"];

buildDropDowns(sizes);
<select id="busMerchPlan" name="busMerchPlan" class="resourceSize"></select>
<select id="busMerchAlloc" name="busMerchAlloc" class="resourceSize"></select>
<select id="busMerchBuy" name="busMerchBuy" class="resourceSize"></select>
<select id="busMerchPDD" name="busMerchPDD" class="resourceSize"></select>

#2


2  

Or you just use the native code new Option( label [,value] )

或者您只需使用本机代码新选项(标签[,值])

A little more minimalistic approach (maybe easier to understand)

一种更简约的方法(可能更容易理解)

var selects = document.getElementsByClassName('resourceSize');
var sizes = ["XXL", "XL", "L", "M", "S", "XS"];

for( var i = 0; i < selects.length; i++ ) {
  for( var id in sizes ) {
    selects[i].options.add( new Option( sizes[id], id ));
  }
}
<select id="busMerchPlan" name="busMerchPlan" class="resourceSize"></select>
<select id="busMerchAlloc" name="busMerchAlloc" class="resourceSize"></select>
<select id="busMerchBuy" name="busMerchBuy" class="resourceSize"></select>
<select id="busMerchPDD" name="busMerchPDD" class="resourceSize"></select>

#3


1  

3 lines of jQuery. Run them after the first <select> has been created. Do not copy and paste, you have to change the #id. Details commented in Demo.

3行jQuery。在创建第一个

Demo

// Each option in #main...
$('#main option').each(function() {

  // ...get this option and copy it and store it in a variable.
  let dupe = $(this).clone();
  
  /* Find all sibling selects that come after #main and add that
  || copy of option to each one
  */
  $('#main').nextAll('select').append(dupe);
});
select {
  display: inline-block;
  font: inherit;
  width: 24%
}
<select id='main' name='main' class='options'>
  <option value=""></option>
  <option value="0">ZER0</option>
  <option value="1">0NE</option>
  <option value="2">TWO</option>
  <option value="3">THREE</option>
  <option value="4">FOUR</option>
</select>
<br><br>


<select id='select0' name='select0' class='options'></select>
<select id='select1' name='select1' class='options'></select>
<select id='select2' name='select2' class='options'></select>
<select id='select3' name='select3' class='options'></select><br>

<select id='select4' name='select4' class='options'></select>
<select id='select5' name='select5' class='options'></select>
<select id='select6' name='select6' class='options'></select>
<select id='select7' name='select7' class='options'></select><br>

<select id='select8' name='select8' class='options'></select>
<select id='select9' name='select9' class='options'></select>
<select id='selectA' name='selectA' class='options'></select>
<select id='selectB' name='selectB' class='options'></select><br>

<select id='selectC' name='selectC' class='options'></select>
<select id='selectD' name='selectD' class='options'></select>
<select id='selectE' name='selectE' class='options'></select>
<select id='selectF' name='selectF' class='options'></select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

#1


3  

Uncaught TypeError: Failed to execute 'add' on 'HTMLOptionsCollection': The provided value is not of type '(HTMLOptionElement or HTMLOptGroupElement)'

未捕获的TypeError:无法在'HTMLOptionsCollection'上执行'add':提供的值不是'(HTMLOptionElement或HTMLOptGroupElement)'的类型

The error message suggests you add a value that's either a HTMLOptionElement or a HTMLOptGroupElement. So, you can write a function that creates such an element :

该错误消息建议您添加一个HTMLOptionElement或HTMLOptGroupElement的值。所以,你可以编写一个创建这样一个元素的函数:

function createOption(option, label) {
      var option = document.createElement("option");
      option.setAttribute("value", option);
      option.innerHTML = label;

      return option;
}

And call it in your selections[i].options.add function.

并在您的选择[i] .options.add函数中调用它。

function buildDropDowns(sizes) {
    var selections = document.getElementsByClassName('resourceSize');
    for(var i=0; i<selections.length; i++) {
      //console.log(selection);
      for(var j= 0; j<sizes.length; j++) {
        selections[i].options.add(createOption(sizes[j], sizes[j]));
      }
    }
}

function createOption(option, label) {
  var option = document.createElement("option");
  option.setAttribute("value", option);
  option.innerHTML = label;
  
  return option;
}
  
var sizes = ["XXL", "XL", "L", "M", "S", "XS"];

buildDropDowns(sizes);
<select id="busMerchPlan" name="busMerchPlan" class="resourceSize"></select>
<select id="busMerchAlloc" name="busMerchAlloc" class="resourceSize"></select>
<select id="busMerchBuy" name="busMerchBuy" class="resourceSize"></select>
<select id="busMerchPDD" name="busMerchPDD" class="resourceSize"></select>

#2


2  

Or you just use the native code new Option( label [,value] )

或者您只需使用本机代码新选项(标签[,值])

A little more minimalistic approach (maybe easier to understand)

一种更简约的方法(可能更容易理解)

var selects = document.getElementsByClassName('resourceSize');
var sizes = ["XXL", "XL", "L", "M", "S", "XS"];

for( var i = 0; i < selects.length; i++ ) {
  for( var id in sizes ) {
    selects[i].options.add( new Option( sizes[id], id ));
  }
}
<select id="busMerchPlan" name="busMerchPlan" class="resourceSize"></select>
<select id="busMerchAlloc" name="busMerchAlloc" class="resourceSize"></select>
<select id="busMerchBuy" name="busMerchBuy" class="resourceSize"></select>
<select id="busMerchPDD" name="busMerchPDD" class="resourceSize"></select>

#3


1  

3 lines of jQuery. Run them after the first <select> has been created. Do not copy and paste, you have to change the #id. Details commented in Demo.

3行jQuery。在创建第一个

Demo

// Each option in #main...
$('#main option').each(function() {

  // ...get this option and copy it and store it in a variable.
  let dupe = $(this).clone();
  
  /* Find all sibling selects that come after #main and add that
  || copy of option to each one
  */
  $('#main').nextAll('select').append(dupe);
});
select {
  display: inline-block;
  font: inherit;
  width: 24%
}
<select id='main' name='main' class='options'>
  <option value=""></option>
  <option value="0">ZER0</option>
  <option value="1">0NE</option>
  <option value="2">TWO</option>
  <option value="3">THREE</option>
  <option value="4">FOUR</option>
</select>
<br><br>


<select id='select0' name='select0' class='options'></select>
<select id='select1' name='select1' class='options'></select>
<select id='select2' name='select2' class='options'></select>
<select id='select3' name='select3' class='options'></select><br>

<select id='select4' name='select4' class='options'></select>
<select id='select5' name='select5' class='options'></select>
<select id='select6' name='select6' class='options'></select>
<select id='select7' name='select7' class='options'></select><br>

<select id='select8' name='select8' class='options'></select>
<select id='select9' name='select9' class='options'></select>
<select id='selectA' name='selectA' class='options'></select>
<select id='selectB' name='selectB' class='options'></select><br>

<select id='selectC' name='selectC' class='options'></select>
<select id='selectD' name='selectD' class='options'></select>
<select id='selectE' name='selectE' class='options'></select>
<select id='selectF' name='selectF' class='options'></select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>