如何添加另一个相同的下拉列表?

时间:2016-09-21 17:01:43

标签: javascript html list

您好我有这个非常简单的代码,以及我正在为学校项目创建的修订时间表。它只是一个简单的下拉列表,允许用户选择他们所做的主题。如何添加一个按钮,在下面创建另一个相同的列表,以便用户可以根据需要添加多个主题?

<!doctype html>
<html>
<head>
<title>Select your subjects</title>
<select id="subject1" name="subject1">
<option value="Maths">Maths</option>
<option value="Physics">Physics</option>
<option value="English">English</option>
<option value="Compting">Computing</option>
</select>
</head>
<body>
</body>
</html>

1 个答案:

答案 0 :(得分:3)

这样的东西?

请注意,我已将select的名称更改为数组[]。因此,当您在服务器端处理数据时,请注意您将处理一个元素数组而不是subject1,subject2,subject3等。

function addCourse() {
  document.getElementById("subjects").innerHTML += '\
<br><select name="subject[]">\
<option value="Maths">Maths</option>\
<option value="Physics">Physics</option>\
<option value="English">English</option>\
<option value="Compting">Computing</option>\
</select>';
}

addCourse();

document.getElementById("add").addEventListener("click", addCourse);
<!doctype html>
<html>

<head>
</head>

<body>
  <form method="post" action="">
    <title>Select your subjects</title>
    <div id="subjects">
    </div>
  </form>
  <input type="button" id="add" value="Add Course">
</body>

</html>

我实际上建议使用下拉列表来指定用户想要的列表数量。所以这样的事情会更好:

var maxCourses = 5;

var select = document.getElementById("num");
var subjects = document.getElementById("subjects");
var previous = 1;

for (var i = 1; i <= maxCourses; i++) {
  var opt = document.createElement('option');
  opt.value = i;
  opt.innerHTML = i;
  select.appendChild(opt);
}

select.addEventListener("change", function() {
  var diff = select.value - previous;
  for (var i = 0; i < Math.abs(diff); i++)
    if (diff > 0)
      addCourse();
    else
      removeCourse();

  previous = select.value;
});

function addCourse() {
  subjects.innerHTML += '\
<select name="subject[]">\
<option value="Maths">Maths</option>\
<option value="Physics">Physics</option>\
<option value="English">English</option>\
<option value="Compting">Computing</option>\
</select>';
}

function removeCourse() {
  subjects.removeChild(subjects.lastChild);
}

addCourse();
select {
  display: block;
}
<!doctype html>
<html>

<head>
</head>

<body>
  <form method="post" action="">
    <title>Select your subjects</title>
    Number of Courses:
    <select id="num"></select><br>
    <div id="subjects">
    </div>
  </form>
</body>

</html>