【问题标题】:Is there a way to combine a dropdown <select> menu with a text field?有没有办法将下拉 <select> 菜单与文本字段结合起来?
【发布时间】:2019-01-24 16:09:09
【问题描述】:

大家下午好 Stackoverflow,

我有以下 javascript 代码,我想在每个“成员”文本字段之前添加一个由数组定义的下拉选择菜单。 选择和文本中的两个值都应该使用模式选择(元素:成员)在 mySQL 中的一个结构化数据值之后保存。 代码中首先定义成员数量的特性应该保持不变。

我已经尝试使用 javascript 来定义第二个 document.createElementById:

var array = ["menu1","menu2","menu3"];
var selectList = document.createElement("select");
selectList.setAttribute("id", "mySelect");

但它似乎没有工作。

<html>
<head>
<script type='text/javascript'>
    function addFields(){
        var number = document.getElementById("member").value;
        var container = document.getElementById("container");
        while (container.hasChildNodes()) {
        container.removeChild(container.lastChild);
        }
        for (i=0;i<number;i++){
            container.appendChild(document.createTextNode("Member " + (i+1)));
            var input = document.createElement("input");
            input.type = "text";
            input.name = "member" + i;
            container.appendChild(input);
            container.appendChild(document.createElement("br"));
        }
    }
</script>
<body>
        <input type="text" id="member" name="member" value="">Number of members: (max. 10)<br/>
        <a href="#" id="filldetails" onclick="addFields()">FillDetails</a>
        <div id="container"/>
</body>
</head>
</html>

代码可以测试http://jsfiddle.net/t656N/1/

我愿意达到的结果是这样的:https://imgur.com/a/RDMjNkx

【问题讨论】:

  • 你看过datalist吗?
  • 是的。但是我将如何在我的函数 addFields() 中实现 datalist?运行函数后,包含文本文件的下拉列表应该可用

标签: javascript text drop-down-menu


【解决方案1】:

使用第二个 for 和一个 createElement 使其工作,如下所示:

<script type='text/javascript'>
function addFields() {
  var number = document.getElementById("member").value;
  var container = document.getElementById("container");
  var optionsSelect = [
    {
      id: 1,
      title: 'Option 1'
    },
    {
      id: 2,
      title: 'Option 2'
    },
    {
      id: 3,
      title: 'Option 3'
    }
  ];

  while (container.hasChildNodes()) {
    container.removeChild(container.lastChild);
  }
  for (i = 0; i < number; i++) {
    var select = document.createElement('select');
    for (var j = 0; j < optionsSelect.length; j++) {
      var options = document.createElement("option");
      options.value = optionsSelect[j].id;
      options.text = optionsSelect[j].title;
      select.appendChild(options);
    }
    container.appendChild(select);
    container.appendChild(document.createTextNode(" -> Description " + (i + 1) + " "));
    var input = document.createElement("input");
    input.type = "text";
    container.appendChild(input);
    container.appendChild(document.createElement("br"));
  }
}
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 2015-04-05
    • 2011-02-12
    • 2013-12-28
    • 1970-01-01
    • 2021-09-20
    • 2021-07-28
    相关资源
    最近更新 更多