chiappa chiappa - 1 month ago 10
jQuery Question

Value name of select option used as number in function

I'm selling 1-2 pieces of apples or oranges in a drop-down list. The value of the items has to be 'apple' and 'oranges' -- so how can I use the parsed names as numbers to count the cost?

<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);
});


https://jsfiddle.net/91Lk7oqo/

Answer
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);
}
});

this works for sure i test it

Comments