Issue
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 smart way to solve it is not by checking the value of every Select. Simply count the amounts of <option>
with the disabled
attribute that is currently selected by using document.querySelectorAll('option[disabled]:checked').length
. Then you you make an simply if comparison with variableName === 0
or simply !variableName
:
const SELECTS = document.querySelectorAll('select');
SELECTS.forEach(select => {
select.addEventListener('change', function() {
let disabledOptionsLength = document.querySelectorAll('option[disabled]:checked').length;
if (!disabledOptionsLength) {
console.log('all selected');
} else {
console.log(`${disabledOptionsLength} options have not been selected`);
}
})
})
<select id="day" name="day">
<option disabled selected>Day</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="month" name="month">
<option disabled selected>Month</option>
<option value="1">January</option>
<option value="2">February</option>
</select>
<select id="year" name="year">
<option disabled selected>Year</option>
<option value="2005">2005</option>
<option value="2004">2004</option>
</select>
Answered By - tacoshy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.