How to put array of elements into a form and not manually?

Viewed 60

How to make a form from an array of items retrieved from a database, and puts each of those elements into the form?

Right now I can't get the items to appear in the form. It's empty.

Here is what I am trying but no luck.

JS file:

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>

In conclusion, I want to make this but showing form options already retrieved from a database and not have to manually add them.

2 Answers

Each <option> needs to be appended to the <select> element. A more idiomatic solution in React would be:

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

You need to append the options to the <select> element. E.g.

    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>

Related