I have three select elements in my HTML code. I want to receive a alert
when all three are selected.
<select id="day" name="day" onchange="report()">
<option disabled selected>Day</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="month" name="month" onchange="report()">
<option disabled selected>Month</option>
<option value="1">January</option>
<option value="2">February</option>
</select>
<select id="year" name="year" onchange="report()">
<option disabled selected>Year</option>
<option value="2005">2005</option>
<option value="2004">2004</option>
</select>
I made it so that it works, but for example when you select day
and month
and change the value of month
again, my code already alerts me but the year was not selected yet. That’s because I used a global variable that increments. I’m looking for a better solution.
var x = 0;
function report() {
x += 1;
if (x == 3) {
alert('All three are selected');
}
}
2
Answers
The problem with your code is that you will trigger the alert if you change any single select 3 times, which isn’t the desired outcome. In the answer below instantiate variables to false for day, month and year. When each one is changed, they get set to true. When all are true, your alert gets triggered.
You don’t need 3 functions for this as just one will do. Within the
report()
function, use the select element id’s to check the state of each select, to see if it has been selected to something other than the default initial value. For example: