Reputation: 49
I have a number of select
inputs, all with the two options
, 'yes' and 'no'.
Every time the 'yes' option is selected, I want to add 1 to a counter. I can do this with the code below.
However, if the user changes the value to 'no' and then back to 'yes' then the counter will be on 2 instead of 1, which isn't wanted.
How do i prevent this so that if they click 'yes' it adds 1, and they then change to 'no' it removes 1. But if they click no first, it remains the same?
var counter = 0;
jQuery("select#select1").change(function(){
var variable1 = jQuery(this).children("option:selected").val();
if (variable1 == 'yes') {
counter++;
alert("Counter:" + counter);
} else {
alert("Counter:" + counter);
}
});
jQuery("select#select2").change(function(){
var variable2 = jQuery(this).children("option:selected").val();
if (variable2 == 'yes') {
counter++;
alert("Counter:" + counter);
} else {
alert("Counter:" + counter);
}
});
jQuery("select#select3").change(function(){
var variable3 = jQuery(this).children("option:selected").val();
if (variable3 == 'yes') {
counter++;
alert("Counter:" + counter);
} else {
alert("Counter:" + counter);
}
});
In this example, the counter should never be able to go higher than 3, as there are only 3 select
fields. (My attempt to resolve problem this was to add the else
and have -1, but this as dumb)
Upvotes: 0
Views: 597
Reputation: 782130
Don't update the counter variable when they select from the menu. When you need the counter, use a loop that counts the number of selects that have the value yes
.
function get_count() {
var counter = 0;
$("select").each(function() {
if ($(this).val() == "yes") {
counter++;
}
});
return counter;
}
$("#show").click(function() {
alert(get_count());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Option 1:
<select id="select1">
<option value="">Please choose</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
<br> Option 2:
<select id="select2">
<option value="">Please choose</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
<br> Option 3:
<select id="select3">
<option value="">Please choose</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
<br>
<button id="show">Show count</button>
Anywhere that you were previously reading the counter
variable, replace that with get_count()
and it will calculate it based on the current selections.
Upvotes: 1