最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding options to multiple Select elements - Stack Overflow

programmeradmin0浏览0评论

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:

$(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.

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

<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?

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.

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:

$(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.

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

<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?

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.

Share Improve this question edited Jun 21, 2018 at 21:50 Barmar 783k56 gold badges547 silver badges660 bronze badges asked Jun 21, 2018 at 21:01 AndrewAndrew 4295 silver badges22 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Uncaught TypeError: Failed to execute 'add' on 'HTMLOptionsCollection': The provided value is not of type '(HTMLOptionElement or 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 :

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.

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>

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 lines of jQuery. Run them after the first <select> has been created. Do not copy and paste, you have to change the #id. Details mented in Demo.

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 e 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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

发布评论

评论列表(0)

  1. 暂无评论