4

I have 3 different dropdowns which are all connected to each other. in the second drop-down options appear based on the selection in the first one...and so on

let's say I select that I have books and movies in the first one.

If I select books ---> the song of ice and fire and a clash of kings appear if I select movies ---> Django Unchained, pulp fiction appear... etc

However, if a user makes "mistake" of choosing the wrong book (let's say the song of ice and fire) and goes back to books ---> the same book is still appearing in the select dropdown.

What I want to do, is "reset" or the clear result of the previously chosen section.

I've tried doing this:

document.getElementById('books').value = "";

but it completely deletes the placeholder of the second dropdown. I want the placeholder to be back to option 0 ---> choose a book

Here is my fiddle

Please help me solve this problem

2
  • So set the value to that first option. Commented Mar 31, 2018 at 14:35
  • The option(s) which you don't wan't, set their css property(display: none;) Commented Mar 31, 2018 at 14:38

2 Answers 2

8

If I understood correctly, you want change the selected option back to default one. To do so, you can do the following:

document.getElementById('books').selectedIndex = 0;

This is just a basic example, where the selected option is switched back to the first one. To do somewhat more advance reset, you could add data-default-index attribute to the rendered select and use that value to reset it back. This way you could use a non-first element as a default one.

Cheers.

Sign up to request clarification or add additional context in comments.

2 Comments

You are welcome. Glad I could help! If one of these answer helped you, please consider marking it as accepted.
yeh it definitely did! i will also research data-default-index. And yes already tried, but i need to wait 5 more mins before accepting
2

Set the selectedIndex to -1 to reset it so no option is selected or to 0 to set it to the first option in the list.

var clk = function() {
  var index = this.dataset.index;
  document.querySelector("#s").selectedIndex = index;
};

document.querySelector("#b1").addEventListener("click",  clk);
document.querySelector("#b2").addEventListener("click",  clk);
<select id="s">
  <option>1 Foo</option>
  <option>2 Foo</option>
  <option>3 Foo</option>
  <option>4 Foo</option>
  </select>
  <button type="button" id="b1" data-index="-1">Change No Selection</button>
  <button type="button" id="b2" data-index="0">Change First Selection</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.