Reputation: 861
I have a drop down menu, which has years listed. Upon selecting a year. The value is calculated based on months in the choose year, like if someone choose 5 years, then 5*12 - months in 5 years , that value then get divided by a certain amount.My loop works fine but if i do each if condition for a dropdown for like 8 years, its 8 loop and in each loop, the amount of months is increased and calculation happen. is there a simple way to do this, instead of me looping it again and again, JSFiddle here.
var yr = document.getElementById("year");
var selected = yr.options[yr.selectedIndex].value;
if(selected == 10){
months = 12 * 10;
amount = 68/months;
alert(amount)
}
Upvotes: 0
Views: 40
Reputation: 13457
I'm not entirely sure if I understood your problem right, but I think this is probably what you're trying to accomplish:
$(function(){
$('#year').change(function(){
var year = document.getElementById("year").value;
year = parseInt(year);
alert( 68/(12*year) );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="year">Year</label>
<select id="year">
<option value="1">1</option>
<option value="5">5</option>
<option value="10" selected>10</option>
<option value="15">15</option>
<option value="30">30</option>
<option value="35">35</option>
<option value="40">40</option>
</select>
Upvotes: 1
Reputation: 21769
You dont need all those ifs, you can do as follows:
var yr = document.getElementById("year");
var selected = yr.options[yr.selectedIndex].value;
months = 12 * parseInt(selected);
amount = 68/months;
alert(amount);
https://jsfiddle.net/ovdcd89m/2/
Upvotes: 1
Reputation: 107536
Yes, you just need to convert the value from the option to a number before you can do the math. For any selected value, try:
months = 12 * parseInt(selected, 10);
amount = 68/months;
alert(amount);
Upvotes: 0