Javascript select选项在值之前保持显示“0”

时间:2014-10-30 20:08:52

标签: javascript parseint

我在获取选项的值并计算它时遇到问题,问题是每当我选择一个选项时,随机的'0'会在它之前显示。任何帮助将不胜感激,这是相关的代码:

               <div class="otherCars">  
                    <label for="otherCars">Do you drive any other cars?</label> 
                    <select name="otherCars" class="style1" id="carsSelect"  onchange="getQuote()" onblur="validateSelect('cars')" >
                        <option value="empty">-Please select-</option>
                        <option value="10" id="car1">No access to any other cars </option>
                        <option value="20">Own another car</option>
                        <option value="100">Named driver on another policy</option>
                        <option value="100">Company car (including personal use)</option>
                        <option value="100">Company car (excluding personal use)</option>
                    </select>
                </div><!-- Closing div tag-->

使用Javascript:

function getQuote(){
var disqualifiedDifference = 0;
var genderDifference = 0;
var carDifference = 0;
var menuSelect = document.getElementById("carsSelect");
var carValue = menuSelect.options[menuSelect.selectedIndex].value;

function genderPrice(){
    if (document.getElementById("male").checked){
        genderDifference += 200;
        }
    if (document.getElementById("female").checked){
        genderDifference += 175;
        }
        } 

function disqoPrice(){
    if (document.getElementById("yes").checked){
        disqualifiedDifference += 300;
        }
    if (document.getElementById("no").checked){
        disqualifiedDifference += 0;
        }
        } 

function carPrice(){
    if (document.getElementById("car1").selected){
        carDifference += 200;
        }
    if (document.getElementById("car2").selected){
        carDifference += 20;
        }
        }



genderPrice();
disqoPrice();

    var totalPrice = disqualifiedDifference + genderDifference + carDifference + carValue;
    document.getElementById('totalPrice').innerHTML = totalPrice;
} //end of CalculateTotal

1 个答案:

答案 0 :(得分:4)

menuSelect.options[menuSelect.selectedIndex].value返回一个字符串,这意味着+运算符将执行字符串连接而不是添加。在尝试算术之前将值转换为Number

var carValue = +menuSelect.options[menuSelect.selectedIndex].value;
//             ^ unary + operator casts a string to a number