Reputation: 6471
I have two select boxes:
<select class="years">
<option value="1">1 year</option>
<option value="5">5 years</option>
</select>
<select class="factor">
<option value="1">normal</option>
<option value="2">double</option>
</select>
When double
is selected I want my years
select box display the double of its values, that means I wish my result to be:
<select class="years">
<option value="2">2 year</option>
<option value="10">10 years</option>
</select>
I do not know how to do this. This is my attempt:
$("select").change(function(){
var factor = $('.factor').find("option:selected").val();
$('.years').find("option").val((this).val*factor );
$('.years').find("option").text((this).val*factor + 'years');
}
https://jsfiddle.net/h6735db4/2/
Upvotes: 1
Views: 134
Reputation: 20750
You can do it like following.
var normal = $('.years option').map(function() {
return this.value;
}).get(); //get initial/normal values
$(".factor").change(function() {
var val = this.value;
$('.years option').each(function(i) {
var value = normal[i] * val;
var text = value == 1 ? value + ' year' : value + ' years';
$(this).val(value).text(text);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="years">
<option value="1">1 year</option>
<option value="5">5 years</option>
</select>
<select class="factor">
<option value="1">normal</option>
<option value="2">double</option>
</select>
Upvotes: 3
Reputation:
Try this example using data
attribute:
$(function() {
$('select.factor').on('change', function() {
var num = +(this.value);
$('select.years option').each(function() {
var opt = $(this);
var yrs = num * +(opt.data('value'));
opt
.val(yrs)
.text(yrs + ' years');
});
})
.trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="years">
<option data-value="1"></option>
<option data-value="5"></option>
</select>
<select class="factor">
<option value="1">normal</option>
<option value="2">double</option>
</select>
Upvotes: 2