Adam Anderson Adam Anderson - 2 months ago 6
HTML Question

How to add another identical dropdown list?

Hi I have this very simple code to go along with a revision timetabler I am creating for a school project. It's just a simple dropwdown list that allows the user to select the subjects they do. How would I add a button that creates another identical list below so the user can add more than 1 subject 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>

Answer

Something like this?

Note that I've changed the name of the select to be an array[]. So when you're processing the data on the server end, just note you'll be handling an array of element and not subject1, subject2, subject3, etc.

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>

I'd actually recommend a dropdown to specify how many lists the user wants. So something like this would be better:

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>

Comments