Revert to original dropdown value if another option is selected

时间:2018-01-15 18:08:15

标签: jquery select dropdown option selectedindex

I need a dropdown list of let's say 10 options to revert to the value="none" starting option if specific other options are selected. How can I grab the value of the dropdown list using selectedIndex?

The below code works, but I would like to grab the values of the selectedIndex -

var ddOptions = document.getElementById("divID").options;
    if (ddOptions.selectedIndex == 2 || ddOptions.selectedIndex == 3 || ddOptions.selectedIndex == 4 || ddOptions.selectedIndex == 7 || ddOptions.selectedIndex == 8)
    ddOptions.selectedIndex = 0;

This is my attempt to grab the values but it is not working -

var ddOptions = document.getElementById("divID");
var ddValue = ddOptions.options[ddOptions.selectedIndex].value;
    if (ddValue == "cat" || ddValue == "dog" || ddValue == "bird" || ddValue == "guinea pig" || ddValue == "rabbit")
    ddValue = "none";

3 个答案:

答案 0 :(得分:0)

Bind an onchange event listener to your list:

    var revertOptions = ['option1', 'option 2', 'option n' ...];

    document.getElementById("#mySelectListId").addEventListener("change", function(e){

      //here you handle the selected element's value
      var selectedValue = e.target[e.target.selectedIndex].value;
      if(revertOptions.indexOf(selectedValue) != -1)
      e.target.selectedIndex = "none";        

    });

答案 1 :(得分:0)

With this you can get the value from the dropdown

$('#divID').val();

With this you can set it back to default

$('#divID').val('');

So you can do something like this:

//Gets the value from dropdown
var ddValue = $('#divID').val();
if (ddValue.equals(0) || ... || ddValue.equals(10))
{
    //Do something

    //Set the dropdown selected value to none
    $('#divID').val('');
}

If you have too many options on your IF, it would be more readable to use a SWITCH statement

答案 2 :(得分:0)

我可能会发表switch声明,而不是像这样将所有内容保持在一条线上。这样它的可读性更高一些,您可以使用我在这里开始的惯例,使其与您需要的其他选项级联。

或者,您可以通过创建一个值数组来使其更加漂亮,然后每次都进行重置,但它会以任何方式工作!

$(".js-select").change(function() {
  let selectedOptionText = $(this).val();
  
  console.log(selectedOptionText + " was selected.");
  
  switch (selectedOptionText) {
    case "cat":
    case "dog":
    case "bird": {
      $(this).val("none");
      break;
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select class="js-select">
  <option value="none" selected>None</option>
  <option value="cat">Cat</option>
  <option value="dog">Dog</option>
  <option value="bird">Bird</option>
  <option value="other">Don't reset if selected</option>
</select>