我在下拉列表中销售1-2件苹果或橙子。项目的价值必须是“苹果”。和橘子' - 那么如何使用解析后的名称作为数字来计算成本呢?
<label>Which Fruit?</label>
<select class="buy" id="fruit">
<option value=""></option>
<option value="apple">Apple $1</option>
<option value="orange">Orange $2</option>
</select>
<label>How Many?</label>
<select class="buy" id="amount">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="text" id="total" readonly="true">
$('.buy').on('change', function() {
var fruit = parseInt($('#fruit').val());
var amount = parseInt($('#amount').val());
var total = fruit * amount;
if(isNaN(total))
$('#total').val('');
else
$('#total').val('$' + total);
});
答案 0 :(得分:1)
var fruit = 0;
var amount = 0;
$('.buy').on('change', function() {
if($(this).attr("id")=="fruit"){
var selectedValue = $(this).val()+"";
console.log(selectedValue);
switch (selectedValue){
case "apple":
fruit = 1; <!-- or whatever value you want -->
break;
case "orange":
fruit = 2;
break;
default:
fruit = 0;
}
}else if($(this).attr("id")=="amount"){
amount = parseInt($('#amount').val());
}
console.log(fruit)
console.log(amount)
var total = fruit * amount;
if(total == 0){
$('#total').val('');
} else{
$('#total').val('$' + total);
}
});
这确实可以测试它
答案 1 :(得分:0)
最好的方法是使用开关案例,如:
var parsedValue = 0;
switch value{
case "Apple":
parsedValue = 1;
...
}
答案 2 :(得分:0)
<label>Which Fruit?</label>
<select class="buy" id="fruit">
<option value=""></option>
<option value="apple">Apple $1</option>
<option value="orange">Orange $2</option>
</select>
<label>How Many?</label>
<select class="buy" id="amount">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="text" id="total" readonly="true">
<script>
var fruit = 0;
$('.buy').on('change', function() {
if($(this).attr("id")=="fruit"){
var selectedValue = $(this).val();
switch (selectedValue){
case "apple":
fruit = 1; <!-- or whatever value you want -->
case "orange":
fruit = 2;
default:
fruit = 0;
}
}
var amount = parseInt($('#amount').val());
var total = fruit * amount;
if(total == 0){
$('#total').val('');
} else{
$('#total').val('$' + total);
}
});
<script>