动态更新多个选择框 [英] Updating Multiple Select Boxes dynamically

查看:25
本文介绍了动态更新多个选择框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,其中有2-300个选择下拉框。我需要动态更新每个选项,以拥有相同的选项列表。每次我尝试更新它时,它只更新第一个。我怀疑问题在于它没有循环通过它。

//HTML

<form id="myForm">
<select id="selectNumber">
<option>Choose a number</option>
</select>
</form>
<form id="myForm">
<select id="selectNumber">
<option>Choose a number</option>
</select>
</form>
<form id="myForm">
<select id="selectNumber">
<option>Choose a number</option>
</select>
</form>

//JAVASCRIPT

    var myArray = new Array("1", "2", "3", "4", "5");


    // Get dropdown element from DOM
    var dropdown = document.getElementById("selectNumber");

    // Loop through the array
    for (var i = 0; i < myArray.length; ++i) {
        // Append the element to the end of Array list
        dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
      }

http://jsfiddle.net/p6eqrxn8/1/

推荐答案

您可以使用getElementById作为表单ID,并将其保存到某个变量

如以下代码所示,然后将该变量用于getElementsByTagName

获取您的所有dropdown表单。

我修改了您的html,请参见下面的内容并使用此脚本

数据-lang="js"数据-隐藏="假"数据-控制台="真">
        window.onload = function() {
          var myFormdropdown = document.getElementById("myForm");
          var varselect = myFormdropdown.getElementsByTagName("select");
          var myArray = new Array("1", "2", "3", "4", "5");
          
          // Loop through the array
          for (var j = 0; j < varselect.length; j++) {
            for (var i = 0; i < myArray.length; ++i) {
              // Append the element to the end of Array list                    
              var option = document.createElement('option');
              option.value = myArray[i];
              option.innerHTML = myArray[i];
              varselect[j].options.add(option);
            }
          }
        };
<form id="myForm">
  <select id="selectNumber">
    <option>Choose a number</option>
  </select>
  <select id="selectNumber">
    <option>Choose a number</option>
  </select>
  <select id="selectNumber">
    <option>Choose a number</option>
  </select>
</form>

希望这将对您有所帮助。

这篇关于动态更新多个选择框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆