使用javascript动态更改列表框

时间:2021-08-01 17:32:11

标签: javascript python html machine-learning flask

我有一个 index.html 文件,其中在下拉列表的 select 标签中使用了多个选项:

streamWriter.WriteLine(JsonConvert.SerializeObject(objDto));
streamWriter.close()

整个 select 标签都在一个表单元素中,基本上是为了使用 Flask 框架为机器学习模型创建一个 web 应用程序。

有没有办法使用javascript,我可以在html中动态生成这个选项值和列表框,

<块引用>

此外,需要分配 0 到 15 之间的相同选项值,因为这将输入到预测模型

提前致谢!

2 个答案:

答案 0 :(得分:0)

您可以将内容存储在数组中,进行迭代,并将选项的值设置为索引:

const values = [
  "10th",
  "11th",
  "12th",
  "1st-4th",
  "5th-6th",
  "7th-8th",
  "9th",
  "Assoc-acdm",
  "Assoc-voc",
  "Bachelors",
  "Doctorate",
  "HS-grad",
  "Masters",
  "Preschool",
  "Prof-school",
  "16 - Some-college"
];
values.forEach((e,i) => edu.innerHTML += `<option value=${i}>${e}</option>`);
<label for="edu">Education</label>
<select id="edu" name="edu"></select>

答案 1 :(得分:0)

您可以通过两种方式做到这一点。

  1. 使用 innerHTML
  2. 直接使用 DOM API 创建事物。

使用 innerHTML

// List of options
const list = ["12th", "11th", "10th"];

// Grabbing the select element from DOM
const selectField = document.getElementById("edu"); // `edu` is the id of select element in html

// DOM string which is about get generated and inserted.
let optionsString = "";

// Generating the string
list.forEach((item, index) => {
  optionsString += ` <option value="${index}">${item}</option>`
});

// Inserting the string
selectField.innerHTML = optionsString;
 <label for="edu">Education</label>
 <select id="edu" name="edu">

  </select>

使用 DOM API

// List of options
const list = ["12th", "11th", "10th"];

// Grabbing the select element from DOM
const selectField = document.getElementById("edu"); // `edu` is the id of select element in html

// Creating and attaching elements on the fly.
list.forEach((item, index) => {
  const option = document.createElement("option");
  option.value = index;
  option.innerText = item;
  selectField.appendChild(option);
});
 <label for="edu">Education</label>
 <select id="edu" name="edu">

  </select>