I want to add the number of 0
that are being selected from the <select>
fields and want to display the addition result into the <input>
field. Also, the value of the <input>
field must change in real time if the user decides to change it to some other value that is not 0
.
Now the issue is, I want to display 2
if both the <select>
field values are 0
and should display 1
if only one of them has 0
value. But, if I am changing the value of either of the <select>
fields two times, the values are changing to 0
. I hope I am making sense.
Please let me know your thoughts.
Thanks!
$(document).ready(function() {
var count = 0;
$('#s1').change(function() {
var f1 = $(this).val();
if (f1 == 0 && f1 != '') {
++count;
} else {
if (count > 0) {
--count;
}
}
$('#total').val(count);
});
$('#s2').change(function() {
var f1 = $(this).val();
if (f1 == 0 && f1 != '') {
++count;
} else {
if (count > 0) {
--count;
}
}
$('#total').val(count);
});
});
<select id="s1">
<option>Select</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="s2">
<option>Select</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="text" id="total" value="0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
2
Answers
Make one function that runs when either input changes. It should check both of the field values and do the appropriate thing.
The logic was initially simple and for 2 elements, but for more than two you do need to count the number of zeroes in the selects. The code for that turns out to be way shorter too, hah.
Similar to @James’s answer, a more "jquery-esq" way would be to use
.filter()
:A single handler for every
select
that recalculates the total every time rather than trying to keep track of a "running total" with + and – values; these frequently go wrong somewhere and you’re left with your total out-of-sync – so just recalculate each time.Updated snippet: