ahmet yılmaz234
ahmet yılmaz234

Reputation: 87

When an option selected I wanna change the other select tags options

In my Django template I have two select tag. I want to change the second tag to be linked to the first. For example when in first tag animals option select I want to show the animals on the second select tag. When plants select in first tag I want to show plants in the second select tag. How can I do this?

       (animals or plants)
      <select id="creatures">
        {% for x in list %}

          <option value="{{x.creature}}">{{x.creature}}</option>

        {% endfor %}
      </select>



          <select id="instances">

            {% for y in instances %}

              <option value="{{y.instance}}">{{x.instance}}</option>

            {% endfor %}
          </select>

Upvotes: 0

Views: 28

Answers (1)

code
code

Reputation: 148

There are multiple ways.

Here is one approach you can take:

Try it in CodeSandbox

document.getElementById("first").addEventListener("change", (e) => {
  const selectedOption = e.target.value;

  // update second select based on what is selected
  document.getElementById("second").innerHTML = getSecondSelectOptions(
    selectedOption
  );
});

function getSecondSelectOptions(category) {
  const animals = ["cat", "dog", "bird"];
  const plants = ["lily", "lotus"];
  if (category === "animals")
    return animals
      .map((value) => `<option value="${value}">${value}</option>`)
      .join("");
  else if (category === "plants")
    return plants
      .map((value) => `<option value="${value}">${value}</option>`)
      .join("");
  else return ""; // clear second select
}

We're updating the contents of the second select using innerHTML.

Another approach would be to have different select elements written statically but hidden by default. Then you can unhide the select element you want based on the option selected in the first select.

Hope it helps.

Upvotes: 1

Related Questions