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');
}
}
>Solution :
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.
let rday = false;
let rmonth = false;
let ryear = false;
function reportDay() {
rday = true
if (rday && rmonth && ryear) {
alert('All three are selected');
}
}
function reportMonth() {
rmonth = true
if (rday && rmonth && ryear) {
alert('All three are selected');
}
}
function reportYear() {
ryear = true
if (rday && rmonth && ryear) {
alert('All three are selected');
}
}
<select onchange="reportDay()">
<option disabled selected>Day</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select onchange="reportMonth()">
<option disabled selected>Month</option>
<option value="1">Januar</option>
<option value="2">Februar</option>
</select>
<select onchange="reportYear()">
<option disabled selected>Year</option>
<option value="2005">2005</option>
<option value="2004">2004</option>
</select>