function ship_stuff()
{
ship_me = document.getElementById("shipMethod").value;
alert(ship_me);
if("ship_me" == "priority2" )
{
document.getElementById("shippingChg").value = 3.20;
}
else if(ship_me == "priority3")
{
document.getElementById("shippingChg").value = 4.30 ;
}
else if(ship_me == "priority4")
{
document.getElementById("shippingChg").value = 5.40 ;
}
else if(ship_me == "overnight")
{
document.getElementById("shippingChg").value = 15.75 ;
}
else if(ship_me == "UPS")
{
document.getElementById("shippingChg").value = 15.00 ;
}
else (ship_me == "free")
{
document.getElementById("shippingChg").value = 0.00 ;
}
代码的HTML部分:
<tr>
<th colspan="4" class="label">Shipping Method:
<select name="shipMethod" id="shipMethod" size="1">
<option value="">Choose a shipping method</option>
<option value="priority2">Priority mail $3.20 (4 items or less)</option>
<option value="priority3">Priority mail $4.30 (6 items or less)</option>
<option value="priority4">Priority mail $5.40 (8 items or less)</option>
<option value="overnight">Express $15.75 (4 items or less only)</option>
<option value="UPS">UPS - 2 day $15.00 (9 - 49 items)</option>
<option value="free">Free shipping (50+ items only)</option>
</select>
</th>
<td><input name="shippingChg" id="shippingChg" type="text" size="10" maxlength="60" value="" /></td>
</tr>
<tr>
当我尝试将我的变量与字符串进行比较时,我的javascript循环失败了。它不会将选项值作为字符串进行比较。我有什么想法可以解决这个问题吗?
感谢您的帮助!
答案 0 :(得分:1)
这很可疑:
if("ship_me" == "priority2" )
你的意思是:
if(ship_me == "priority2" )
您可能还想将ship_me声明为var:
var ship_me = document.getElementById("shipMethod").value;
显式转换为字符串可以这样完成:
ship_me = String(ship_me);
答案 1 :(得分:1)
ship_me = document.getElementById("shipMethod").options[document.getElementById("shipMethod").selectedIndex];
这是获取所选选项的正确方法。
答案 2 :(得分:1)
你在最后的else子句中错过了if
。如果您希望它始终运行,请删除括号中的条件。
另外,尝试映射而不是if / else链:
var shippingCharges = {
"priority2" : 3.20,
"priority3": 4.30,
"priority4" : 5.40,
"overnight": 15.75,
"UPS": 15.00,
"free": 0.00
};
document.getElementById("shippingChg").value = shippingCharges[ship_me];
答案 3 :(得分:1)
嘿马特,请帮个忙,然后使用这段代码:
var shipping_costs = {
'priority2': 3.2,
'priority3': 4.3,
'priority4': 5.4,
'overnight': 15.75,
'UPS': 15.0,
'free': 0.0
};
var method = document.getElementById('shipMethod').value;
document.getElementById("shippingChg").value = shipping_costs[method] || 0.0;
这就是它的全部。请注意,我将描述性选项<option value="">Choose a shipping method</option>
(用户未选择任何内容)映射到免费送货方式。