I tried to write some jQuery functions to change some variables values when options of a select item are selected (add a certain value if option is selected, subtract that value if option is not selected anymore), but it adds and subtracts values in a very odd way. Here's the code I wrote for the javascript (adapted from a previous code that used to work with checkboxes):
var pds1=0;
var pds2=0;
var pds3=0;
var pdstot=0;
$(document).ready(function() {
$('#perk1').html(pds1);
$('#perk2').html(pds2);
$('#perk3').html(pds3);
$('#perktot').html(pdstot);
$("#blabla").change(
function() {
if ($("option#5:selected").length)
{
pds1=pds1+10;
pdstot=pdstot+10;
}
else if(pds1>0)
{
pds1=pds1-10;
pdstot=pdstot-10;
}
if ($("option#3:selected").length)
{
pds2=pds2+10;
pdstot=pdstot+10;
}
else if(pds2>0)
{
pds2=pds2-10;
pdstot=pdstot-10;
}
if ($("option#4:selected").length)
{
pds3=pds3+10;
pdstot=pdstot+10;
}
else if(pds3>0)
{
pds3=pds3-10;
pdstot=pdstot-10;
}
//option 6 adds 10 to variable pds1 and pds2
if ($("option#6:selected").length)
{
pds1=pds1+10;
pds2=pds2+10;
pdstot=pdstot+10;
}
else if(pds1>0)
{
pds1=pds1-10;
pds2=pds2-10;
pdstot=pdstot+10;
}
$('#perk1').html(pds1);
$('#perk2').html(pds2);
$('#perk3').html(pds3);
$('#perktot').html(pdstot);
});
});
and here's the html
<select id='blabla' multiple='multiple'>
<option id='5'>Name5</option>
<option id='3'>Name3</option>
<option id='4'>Name4</option>
<option id='6'>Name6</option>
</select>
<span id="perk1"></span>
<span id="perk2"></span>
<span id="perk3"></span>
<span id="perk4"></span>
Can someone explain me how this function is handling variables? Odd behavior example: clicking option 5 doesn't add 10 to pds1, but instead it subtracts 10 to pds2; what I'd like to happen instead it's to add 10 to pds1 and do nothing to pds2. I think the problem, in this case, it's in the "else if" under "option#6:selected", but why? And it's not the only odd behavior.
option#4