How do I check if I have selected the same drop-down list option twice in a row?

Tags: ,



Let’s supose I have a simple drop-down list from which I can freely select any option I want.

I can, via JavaScript, store the selected option’s value in a variable this way:

var checkValue = function(){
  const mySelect = document.getElementById("cars");
  let currentValue =  mySelect.options[ mySelect.selectedIndex ].value;
  console.log(currentValue);
}
<select id="cars" onchange="checkValue()">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

Questions:

  1. How can I check if I have selected the same drop-down list option twice in a row, in other words, if the value of currentValue has changed?

  2. Would using AngularJS make this task easier? How?

Answer

var arr = [];
var checkValue = function() {
  const mySelect = document.getElementById("cars");
  let currentValue = mySelect.options[mySelect.selectedIndex].value;

  if ($.inArray(currentValue, arr) != "-1") {
    console.log("already selected");
  } else {
    arr.push(currentValue);
    console.log(currentValue);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<select id="cars" onchange="checkValue()">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>


Source: stackoverflow