【问题标题】:How to put array of elements into a form and not manually?如何将元素数组放入表单而不是手动?
【发布时间】:2021-04-08 18:36:34
【问题描述】:

如何根据从数据库中检索到的项目数组制作表单,并将这些元素中的每一个放入表单中?

现在我无法让这些项目出现在表单中。是空的。

这是我正在尝试的,但没有运气。

JS 文件

function input(items) {
    var arr = [];
      for (var i = 0; i < this.state.items.length; i++) {
        arr.push(this.state.items[i].name)
      }
      arr.forEach(function(item) {
        var source = document.getElementById("cowNames[]")
        var option = document.createElement("option");
        option.text = item;
        source.append(option, source[0])
    });
};

HTML

<form name="submit" onSubmit={this.handleSubmit}>
    <label>
        Find Item:
        <select>
            <option id="cowNames[]" className="items">
            </option>
        </select>
    </label>
    <input type="submit" value="View Info" />
</form>

总之,我想做这个,但显示已经从数据库中检索到的表单选项,而不必手动添加它们。

【问题讨论】:

  • 你在使用 React 吗?如果是,您可以添加整个组件吗?

标签: javascript html reactjs forms


【解决方案1】:

您需要将选项附加到&lt;select&gt; 元素。例如

    var arr =  ['dexter','aberdeen','hereford']
      arr.forEach(function(item) {
        var source = document.getElementById("cowNames[]")
        var option = document.createElement("option");
        option.classList.add("items");
        option.text = item;
        source.append(option, source[0])
        })
      <form name="submit" onSubmit={this.handleSubmit}>
        <label>
          Find Item:
          <select id="cowNames[]">

          </select>
        </label>
        <input type="submit" value="View Info" />
      </form>

【讨论】:

  • 只想说,如果 OP 使用 React,这可以以更好的方式完成
  • @RameshReddy 为什么不作为另一个答案发布?我不是一个反应用户,所以想了解它会如何更好......
  • 在这种情况下我们不需要查询元素。看看 juliomalves 的回答。
  • @RameshReddy,谢谢,这很整洁!
【解决方案2】:

每个&lt;option&gt; 都需要附加到&lt;select&gt; 元素。 React 中更惯用的解决方案是:

// Assuming `optionsArr` contains your option values
<form name="submit" onSubmit={this.handleSubmit}>
  <label>
    Find Item:
    <select>
      {optionsArr.map((optionName) => (
        <option value={optionName}>{optionName}</option>
      ))}
    </select>
  </label>
  <input type="submit" value="View Info" />
</form>

【讨论】:

  • 是的,这行得通!太感谢了!偏头痛消失了。
猜你喜欢
  • 2016-06-27
  • 1970-01-01
  • 1970-01-01
  • 2011-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-20
相关资源
最近更新 更多