我的javascript函数返回正确值时遇到问题。因此,基本上,我期望出现的是tour_prices-arraylist中的价格之一。但是实际上什么也没有出现。任何帮助表示赞赏。
var tour_prices = new Array();
tour_prices["0"]=3000;
tour_prices["1"]=4400;
tour_prices["2"]=5500;
tour_prices["3"]=6600;
tour_prices["4"]=7700;
function tourPrice() {
var thePrice = 0;
var scheme = document.forms["orderScheme"];
var pickDestination = scheme.elements["destination"];
thePrice = tour_prices[pickDestination.value];
return thePrice;
}
function calculateTotal() {
var totalTourPrice = tourPrice();
var totalPrice = document.getElementById('totalPrice');
totalPrice.innerHTML = "the total tour price is " + totalTourPrice + " usd.";
}
<form action="" id="orderScheme" onsubmit="return false">
<div>
<fieldset>
<legend>Order cruise!</legend>
<b><label>Pick Destination: </label></b>
<select id="destination" name='destination' onchange="calculateTotal()">
<option value="0">destination 1</option>
<option value="1">destination 2</option>
<option value="2">destination 3</option>
<option value="3">destination 4</option>
<option value="4">destination 5</option>
</select>
</fieldset>
<div id="totalPrice" name="totalPrice"></div><br>
<input type='submit' id='submit' value='calculate' onclick="calculateTotal()"></input>
</form>
最佳答案
select
没有自己的value
-您需要找到所选的option
(通过selectedIndex
属性),然后获取其值。
var tour_prices = new Array();
tour_prices["0"]=3000;
tour_prices["1"]=4400;
tour_prices["2"]=5500;
tour_prices["3"]=6600;
tour_prices["4"]=7700;
function tourPrice() {
var thePrice = 0;
var scheme = document.forms["orderScheme"];
var pickDestination = scheme.elements["destination"];
var val = pickDestination.options[ pickDestination.selectedIndex ].value;
thePrice = tour_prices[val];
return thePrice;
}
function calculateTotal() {
var totalTourPrice = tourPrice();
var totalPrice = document.getElementById('totalPrice');
totalPrice.innerHTML = "the total tour price is " + totalTourPrice + " usd.";
}
<form action="" id="orderScheme" onsubmit="return false">
<div>
<fieldset>
<legend>Order cruise!</legend>
<b><label>Pick Destination: </label></b>
<select id="destination" name='destination' onchange="calculateTotal()">
<option value="0">destination 1</option>
<option value="1">destination 2</option>
<option value="2">destination 3</option>
<option value="3">destination 4</option>
<option value="4">destination 5</option>
</select>
</fieldset>
<div id="totalPrice" name="totalPrice"></div><br>
<input type='submit' id='submit' value='calculate' onclick="calculateTotal()"></input>
</form>