显示基于选择菜单选项的 JavaScript 计算

发布于 2024-11-04 04:03:42 字数 2610 浏览 3 评论 0原文

这对某人来说应该是一个扣篮。我是一个完全的 Javascript 新手,以至于我很惊讶我已经走到了这一步。以至于当你查看我的代码时,你很可能会立即看到它的明显问题并嘲笑我,因为我此时正在盲目猜测语法。请参阅下面的违规代码并享受欢笑。我会等待。

好的,所以我正在尝试制作一个简单的计算器,显示购买公交卡与支付现金相比每月节省的费用。我试图根据选择菜单中选择的区域显示不同的答案。当我简单地列出 if 语句之外的变量(因此我前面提到的感到惊讶),在一系列警报框中显示每个答案时,每个 if 语句中的公式实际上确实有效,但我只想显示适用的答案,并且清楚地显示我的语法完全不正常。

我很荣幸也很荣幸能在这方面接受教育,当然要记住我的 JS 技能还不那么初级。提前谢谢。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Cost Savings Calculator</title>



<script language="JavaScript">

<!-- Begin CE MP Savings Calc script
function  doMath3() {
var one = eval(document.theForm3.elements[0].value)
var two = eval(document.theForm3.elements[1].value)
var three = eval(document.theForm3.elements[3].value)

if(document.theForm3.elements[3].value = "z4"){
var prodZ4 = (((one  *   two) * 4.25) *12) - 1680
alert("Your yearly savings if you buy a Commuter Express Zone 4 monthly pass is $"  +  prodZ4  +  ".")
}

if(document.theForm3.elements[3].value = "z3"){
var prodZ3 = (((one  *   two) * 3.75) *12) - 1488
alert("Your yearly savings if you buy a Commuter Express Zone 3 monthly pass is $"  +  prodZ3  +  ".")
}

if(document.theForm3.elements[3].value = "z2"){
var prodZ2 = (((one  *   two) * 3) *12) - 1200
alert("Your yearly savings if you buy a Commuter Express Zone 2 monthly pass is $"  +  prodZ2  +  ".")
}

if(document.theForm3.elements[3].value = "z1"){
var prodZ1 = (((one  *   two) * 2.5) *12) - 960
alert("Your yearly savings if you buy a Commuter Express Zone 1 monthly pass is $"  +  prodZ1  +  ".")
}

if(document.theForm3.elements[3].value = "Base"){
var prodBase = (((one  *   two) * 1.5) *12) - 684
alert("Your yearly savings if you buy a Commuter Express Base monthly pass is $"  +  prodBase  +  ".")
}

}
// End CE MP Savings Calc script -->
</script>



</head>

<body>

<form name="theForm3">
Days you commute monthly:
<input type="text">
Daily trips on Commuter Express:
<input type="text">
Choose Zone: <select name="zone">
<option value="Base">Base</option>
<option value="z1">Zone 1</option>
<option value="z2">Zone 2</option>
<option value="z3">Zone 3</option>
<option value="z4">Zone 4</option>
</select>
<input type="button" value="Show result" onclick="doMath3()">

</form>


</body>
</html>

This one ought to be a slam dunk for somebody. I am a total Javascript novice, so much so that I'm amazed I've gotten this far. So much so that when you look at my code, you'll very likely immediately see glaring problems with it and laugh at me, because I am blindly guessing at syntax at this point. Please see the offending code below and enjoy a chuckle. I'll wait.

Okay, so I'm trying to make a simple calculator that displays the monthly savings of buying a bus pass over paying cash. I'm trying to display a different answer depending upon the zone chosen in the select menu. The formulas in each if statement does actually work when I simply list the variables outside of if statements (hence my aforementioned amazement), displaying each answer in a series of alert boxes, but I'd like to display only the applicable answer, and clearly my syntax is all out of whack.

I'd be honored and humbled to be schooled in this matter, bearing in mind of course my less-than-rudimentary JS skills. Much advance thanks.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Cost Savings Calculator</title>



<script language="JavaScript">

<!-- Begin CE MP Savings Calc script
function  doMath3() {
var one = eval(document.theForm3.elements[0].value)
var two = eval(document.theForm3.elements[1].value)
var three = eval(document.theForm3.elements[3].value)

if(document.theForm3.elements[3].value = "z4"){
var prodZ4 = (((one  *   two) * 4.25) *12) - 1680
alert("Your yearly savings if you buy a Commuter Express Zone 4 monthly pass is $"  +  prodZ4  +  ".")
}

if(document.theForm3.elements[3].value = "z3"){
var prodZ3 = (((one  *   two) * 3.75) *12) - 1488
alert("Your yearly savings if you buy a Commuter Express Zone 3 monthly pass is $"  +  prodZ3  +  ".")
}

if(document.theForm3.elements[3].value = "z2"){
var prodZ2 = (((one  *   two) * 3) *12) - 1200
alert("Your yearly savings if you buy a Commuter Express Zone 2 monthly pass is $"  +  prodZ2  +  ".")
}

if(document.theForm3.elements[3].value = "z1"){
var prodZ1 = (((one  *   two) * 2.5) *12) - 960
alert("Your yearly savings if you buy a Commuter Express Zone 1 monthly pass is $"  +  prodZ1  +  ".")
}

if(document.theForm3.elements[3].value = "Base"){
var prodBase = (((one  *   two) * 1.5) *12) - 684
alert("Your yearly savings if you buy a Commuter Express Base monthly pass is $"  +  prodBase  +  ".")
}

}
// End CE MP Savings Calc script -->
</script>



</head>

<body>

<form name="theForm3">
Days you commute monthly:
<input type="text">
Daily trips on Commuter Express:
<input type="text">
Choose Zone: <select name="zone">
<option value="Base">Base</option>
<option value="z1">Zone 1</option>
<option value="z2">Zone 2</option>
<option value="z3">Zone 3</option>
<option value="z4">Zone 4</option>
</select>
<input type="button" value="Show result" onclick="doMath3()">

</form>


</body>
</html>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

策马西风 2024-11-11 04:03:43

这是一种方法:

function  doMath3() {
    var one = parseInt(document.theForm3.elements[0].value);
    var two = parseInt(document.theForm3.elements[1].value);
    var selection = document.getElementsByName("zone")[0].value;

    if(selection === "z4"){
        var prodZ4 = (((one  *   two) * 4.25) *12) - 1680;
        alert("Your yearly savings if you buy a Commuter Express Zone 4 monthly pass is $"  +  prodZ4  +  ".");
    }
    else if(selection === "z3"){
        var prodZ3 = (((one  *   two) * 3.75) *12) - 1488;
        alert("Your yearly savings if you buy a Commuter Express Zone 3 monthly pass is $"  +  prodZ3  +  ".");
    }
    else if(selection === "z2"){
        var prodZ2 = (((one  *   two) * 3) *12) - 1200;
        alert("Your yearly savings if you buy a Commuter Express Zone 2 monthly pass is $"  +  prodZ2  +  ".");
    }
    else if(selection === "z1"){
        var prodZ1 = (((one  *   two) * 2.5) *12) - 960;
        alert("Your yearly savings if you buy a Commuter Express Zone 1 monthly pass is $"  +  prodZ1  +  ".");
    }
    else if(selection === "Base"){
        var prodBase = (((one  *   two) * 1.5) *12) - 684;
        alert("Your yearly savings if you buy a Commuter Express Base monthly pass is $"  +  prodBase  +  ".");
    }
}

修复:

  1. 你到处都缺少;(分号) - 它们对于开发人员来说似乎是“可选的”,但在内部,JavaScript会自动添加它们导致难以追踪错误。在每个语句的末尾添加一个。

  2. 正如其他地方提到的,不要使用 eval(),使用 parseInt() 获取整数,使用 parseDouble() 获取浮点数.

  3. = 是赋值运算符,===== 用于检查相等性。在这两者中,=== 应该是首选。 == 将执行强制转换,而 === 则不会。

  4. 我认为最大的问题是 document.theForm3.elements[3].value 获取按钮而不是选择框。它应该是索引 2。

可选:

  1. 您可以使用 else if,因为任何时候只有一个条件可能为真。您还可以使用 switch-case 代替。

  2. 我还会避免使用索引来获取元素,因为您可能决定稍后更改表单,并且确保正确更新所有索引将会很痛苦。请查看 getElementsById。正如 @Frits 在下面的评论中指出的那样,您还可以使用语法 document.formname.inputname (即 document.theForm3.zone.value; 对于您的表单)来获取元素更加干净和安全。

这是一个工作示例

Here's one way of doing it:

function  doMath3() {
    var one = parseInt(document.theForm3.elements[0].value);
    var two = parseInt(document.theForm3.elements[1].value);
    var selection = document.getElementsByName("zone")[0].value;

    if(selection === "z4"){
        var prodZ4 = (((one  *   two) * 4.25) *12) - 1680;
        alert("Your yearly savings if you buy a Commuter Express Zone 4 monthly pass is $"  +  prodZ4  +  ".");
    }
    else if(selection === "z3"){
        var prodZ3 = (((one  *   two) * 3.75) *12) - 1488;
        alert("Your yearly savings if you buy a Commuter Express Zone 3 monthly pass is $"  +  prodZ3  +  ".");
    }
    else if(selection === "z2"){
        var prodZ2 = (((one  *   two) * 3) *12) - 1200;
        alert("Your yearly savings if you buy a Commuter Express Zone 2 monthly pass is $"  +  prodZ2  +  ".");
    }
    else if(selection === "z1"){
        var prodZ1 = (((one  *   two) * 2.5) *12) - 960;
        alert("Your yearly savings if you buy a Commuter Express Zone 1 monthly pass is $"  +  prodZ1  +  ".");
    }
    else if(selection === "Base"){
        var prodBase = (((one  *   two) * 1.5) *12) - 684;
        alert("Your yearly savings if you buy a Commuter Express Base monthly pass is $"  +  prodBase  +  ".");
    }
}

Fixes:

  1. You're missing ; (semi-colon's) everywhere - they might seem to be 'optional' for the developer but internally, JavaScript will add them automatically leading to hard to track bugs. Put one at the end of every statement.

  2. As mentioned elsewhere, don't use eval(), use parseInt() to get integers and parseDouble() to get floats.

  3. = is the assignment operator, == and === are used to check equality. Of these two, === should be preferred. == will perform coercion while === will not.

  4. The biggest problem I think was that document.theForm3.elements[3].value gets the button and not the select box. It should be index 2.

Optionally:

  1. You could use else ifs since only one of the conditions could be true at any time. You could also use switch-case instead.

  2. I would also avoid using indexes to get the elements since you might decide to change the form later and it's going to be painful to make sure you update all the indices correctly. Check out getElementsById instead. As @Frits notes in the comment below, you could also use the syntax document.formname.inputname (i.e. document.theForm3.zone.value; for your form) to get the element much more cleanly and safely.

Here's a working example.

掀纱窥君容 2024-11-11 04:03:43

您的 if 语句是分配而不是比较。有关详细信息,请参阅 http://www.w3schools.com/js/js_comparisons.asp JavaScript 中的比较器。

if ( a == b )

检查 a 是否等于 b

if ( a = b )

将 a 设置为等于 b 的值,然后返回 true,即始终通过。

这是您遇到的一个值得注意的错误,尽管我不能确定它是导致您问题的原因。

Your if statements are assigning instead of comparing. See http://www.w3schools.com/js/js_comparisons.asp for details on comparitors in javascript.

if ( a == b )

checks to see if a is equal to b

if ( a = b )

sets a equal to the value of b and then returns true, ie this always passes.

Thats one noticable error you have, though I can't be certain its the one causing your issue.

云巢 2024-11-11 04:03:43

将 eval 更改为:

parseFloat(document.theForm3.elements[0].value, 10);

赋值而不是比较:

if(document.theForm3.elements[3].value = "Base"){

更改为:

if(document.theForm3.elements[3].value === "Base"){

选择框没有 value 属性(尽管现代浏览器接受它)

document.theForm3.elements[3].value

正确的方法:

var select = document.theForm3.elements[2];
select.options[select.selectedIndex].value; // <-- this is the 'value'

我认为这应该修复您的代码。

Change eval to:

parseFloat(document.theForm3.elements[0].value, 10);

Assignment instead of comparison:

if(document.theForm3.elements[3].value = "Base"){

Change to:

if(document.theForm3.elements[3].value === "Base"){

Select boxes don't have a value property (although modern browsers accept it)

document.theForm3.elements[3].value

Correct way:

var select = document.theForm3.elements[2];
select.options[select.selectedIndex].value; // <-- this is the 'value'

I think that should fix your code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文