Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to reset values of select dropdown

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

like image 571
aiden87 Avatar asked Oct 19 '25 13:10

aiden87


2 Answers

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.

like image 123
Mladen Ilić Avatar answered Oct 21 '25 01:10

Mladen Ilić


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>
like image 43
epascarello Avatar answered Oct 21 '25 01:10

epascarello



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!