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:
JavaScript
x
5
1
var checkValue = function(){
2
const mySelect = document.getElementById("cars");
3
let currentValue = mySelect.options[ mySelect.selectedIndex ].value;
4
console.log(currentValue);
5
}
JavaScript
1
6
1
<select id="cars" onchange="checkValue()">
2
<option value="volvo">Volvo</option>
3
<option value="saab">Saab</option>
4
<option value="opel">Opel</option>
5
<option value="audi">Audi</option>
6
</select>
Questions:
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?Would using AngularJS make this task easier? How?
Advertisement
Answer
JavaScript
1
12
12
1
var arr = [];
2
var checkValue = function() {
3
const mySelect = document.getElementById("cars");
4
let currentValue = mySelect.options[mySelect.selectedIndex].value;
5
6
if ($.inArray(currentValue, arr) != "-1") {
7
console.log("already selected");
8
} else {
9
arr.push(currentValue);
10
console.log(currentValue);
11
}
12
}
JavaScript
1
8
1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
2
3
<select id="cars" onchange="checkValue()">
4
<option value="volvo">Volvo</option>
5
<option value="saab">Saab</option>
6
<option value="opel">Opel</option>
7
<option value="audi">Audi</option>
8
</select>