看着你的表格,
1)我认为总夜数的下拉列表是多余的(总夜数从到达和离开日期就很清楚了)
2) 日期(为了在 JavaScript 中更简单地使用它)使用数值而不是:'11/05/2013(A)' 等。
<select name="ArrivalDate" size="1" id="ArrivalDate">
<option>Please select</option>
<option value="1368399600">13-05-2013</option>
<option value="1368486000">14-05-2013</option>
...
</select>
3)我没有注意到每晚的价格?也许酒店列表也可能包含一些 ID(例如 h1a、h1b、h2a、h3a、h3b、h3c ......)而不是文本选项描述(酒店和房间)
<select name="hotel_choice" id="hotel5">
<option value="nothing" selected="selected">None Selected</option>
<option value='nothing'>.</option>
<option value="h1a">Corinthia Single Room</option>
<option value="h1b">Corinthia Double Room</option>
<option value='nothing'>.</option>
...
</select>
如果您这样做,那么 JavaScript 可能不会那么复杂(假设您进行了这些更改并且不介意在页面源中显示每家酒店的价格):
<script type='text/javascript'>
var prices={nothing:0,h1a:357,h1b:280.50,h2a:380}; //here are your hotel prices
function calculate() {
var days = Math.round( (
document.getElementById('datedepart').value -
document.getElementById('ArrivalDate').value
) / 86400 ); //timestamp is in seconds
document.getElementById('total_cost').value =
days *
prices[ document.getElementById('hotel5').value ];
}
</script>
请注意,代码中没有任何细节,它基于这样的假设,即日期更改为它们的代表整数值(例如由 php 函数 time() 返回),也有可能我犯了一个错误在元素的 ID 名称中
然后剩下的就是连接“calculate();” javascript函数到所有控件的onchange事件,你就完成了。
<select name="hotel_choice" id="hotel5" onchange='calculate();'>
...
</select>
和
<select name="ArrivalDate" size="1" id="ArrivalDate" onchange='calculate();'>
...
</select>
在出发日期选择器中也是如此。
编辑:
您可以在日期选择器中使用日期,但您必须使用以下方式将该字符串解析为数字客户端:
var dt=Date.parse(document.getElementById('ArrivalDate').value);
但请务必检查此函数支持的日期格式,并注意它返回自 1970 年以来的毫秒数,因此您必须除以 86400000 而不是 86400
编辑 - 检查日期已填写
function calculate() {
var dd=document.getElementById('datedepart');
var da=document.getElementById('ArrivalDate');
var total=document.getElementById('total_cost');
var hotel=document.getElementById('hotel5');
//no hotel room selected or not depart date set or not arrival date set
//or departing before arrival (nonsense) - set total to ZERO and exit the function
if ( !(dd.value*1) || !(da.value*1) || da.value>dd.value ) {
total.value='0';//you can set it to 'not allowed' also if you wish (instead of '0')
return;
}
var days = Math.round( (
dd.value -
da.value
) / 86400 ); //timestamp is in seconds
var cost = days * prices[ hotel.value ];
if (isNaN(cost))
cost = 0; //or set to "invalid input" - but this line should not be needed at this point
total.value = cost;
}