如何使用相同的选项元素填充两个或更多选择

时间:2018-04-09 09:38:19

标签: javascript html

我想使用一个JavaScript函数将相同的选项元素添加到多个选项中。



<select id="select1" name="select1"></select>
<select id="select2" name="select2"></select>
&#13;
&#13;
&#13;

我想选择成为:

&#13;
&#13;
<select id="select1" name="select1"> 
  <option value="0">Txt1</option>
  <option value="1">Txt2</option>
  <option value="2">Txt3</option>
</select>
<select id="select2" name="select2"> 
  <option value="0">Txt1</option>
  <option value="1">Txt2</option>
  <option value="2">Txt3</option>
</select>
&#13;
&#13;
&#13;

以下是使用选项填充选项的功能的一部分:

function window_onload(){
  var SpecTxt = new Array("Txt1","Txt2","Txt3");
    for(var i=0; i<SpecTxt.length; i++) {
      var oOption = document.createElement("OPTION");
          oOption.text = SpecTxt[i];
          oOption.value=i;
          select1.add(oOption);  // Option to first SELECT
          select2.add(oOption);  // Option to second SELECT
    }
}

但我已经获得了Internet Explorer脚本错误&#34;无效的参数&#34;,结果只是&#34; select1&#34;中的第一个选项。 &#34; select2&#34;中没有选项。如果我从功能window_onload()中移除最后一个字符串 select2.add(oOption); ,则没有IE错误和&#34; select1&#34;必须填写,但是&#34; select2&#34;是空的。如何在JS中为不同的SELECT添加相同的选项?

1 个答案:

答案 0 :(得分:1)

更新

Demo之所以不适用于IE,是因为它无法识别属性.valueAsNumber

发件人:

var opts = qty.valueAsNumber;

var opts = parseInt(qty.value, 10);

在循环中创建选项时:

var oOption = document.createElement("OPTION");

只有一个<option>而不是两个<option>。这就是为什么:

select1.add(oOption);  // Succeeds
select2.add(oOption);  // Fails

你可以为每个循环制作2 <option>

var oOption1 = document.createElement("OPTION");
var oOption2 = document.createElement("OPTION");

或尝试cloneNode()。见下面的演示:

演示

&#13;
&#13;
// See HTMLFormControlsCollection
var form = document.forms.ui;
var ui = form.elements;
var qty = ui.qty0;
var s0 = ui.sel0;
var s1 = ui.sel1;

// Declare a counter variable outside of loop
var cnt = 0;

// Add event handler to the change event of the input
qty.onchange = addOpt;

/* Get the value of user input as a number
|| within the for loop...
|| create an <option> tag...
|| add text to it with an incremented offset...
|| add a incremented value to it...
|| then clone it...
|| add original <option> to the first <select>...
|| add duplicate <option> to the second <select>
*/
function addOpt(e) {
  var opts = parseInt(qty.value, 10);
  for (let i = 0; i < opts; i++) {
    var opt = document.createElement('option');
    opt.text = 'Txt' + (cnt + 1);
    opt.value = cnt;
    var dupe = opt.cloneNode(true);
    s0.add(opt);
    s1.add(dupe);
    cnt++;
  }
}
&#13;
input,
select,
option {
  font: inherit
}

input {
  width: 4ch;
}
&#13;
<form id='ui'>
  <fieldset>
    <legend>Enter a number in the first form field</legend>
    <input id='qty0' name='qty0' type='number' min='0' max='30'>
    <select id="sel0" name="sel0"></select>
    <select id="sel1" name="sel1"></select>
  </fieldset>
</form>
&#13;
&#13;
&#13;

参考

HTMLFormControlsCollection