How to add another identical drop down list?

Hi, I have this very simple code that will help you create a temporary change list that I am creating for a school project. This is just a simple list that allows the user to select the topics that they perform. How would I add a button that creates another identical list below so that the user can add more than one item if they wish?

<!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>
+4
source share
1 answer

Something like that?

, 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>
Hide result

, , . :

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>
Hide result
+3

Source: https://habr.com/ru/post/1655369/


All Articles