gpt4 book ai didi

javascript - 在 Javascript 中使用多个选项进行计算

转载 作者:行者123 更新时间:2023-11-27 23:30:45 24 4
gpt4 key购买 nike

我对 Javascript 很陌生,已经开始做简单的计算,但遇到了 <select> 的障碍。

我希望代码获取用户在下拉菜单中选择的内容,并乘以“多少晚?”中的数字。盒子。答案将显示在下面的文本框中。选择菜单中的选项都有与其相关的价格。

< script language = "javascript" >
function calculate() {
var val1 = parseInt(document.getElementById("Nights").value);
var val1 = parseInt(document.getElementById("House").value);
var House1 = 100;
var House2 = 175;
var House3 = 150;
var House4 = 135;
var House5 = 150;
var House6 = 120;
var House7 = 180;
var House8 = 120;
var House9 = 80;
var House10 = 105;

var ansD = document.getElementById("answer");
ansD.value = House * Nights;
}
} < /script>

<html>

<head>
<title>Calculate cost</title>



</head>

<body>
<select required class="textfield" name="House" id="House">
<option value="">None</option>
<option value="House1">House 1</option>
<option value="House2">House 2</option>
<option value="House3">House 3</option>
<option value="House4">House 4</option>
<option value="House5">House 5</option>
<option value="House6">House 6</option>
<option value="House7">House 7</option>
<option value="House8">House 8</option>
<option value="House9">House 9</option>
<option value="House10">House 10</option>
</select>
<br />
<br />How many nights?
<input type="text" id="Nights" name="Nights" value="1" />

<input type="button" name="Submit" value="Cost" onclick="javascript:addNumbers()" />
<br />
<br />Your stay will cost £
<input type="text" id="answer" name="answer" value="" />
</body>

</html>

最佳答案

通过在选择下拉列表中设置房屋的值,您可以帮助自己很多。您可以看到 javascript 部分大大减少了,而且将这些值加在一起实际上非常简单

此外,重要的是您的按钮不是提交类型,因为它会提交您的脚本,而且您不会看到计算函数的结果;)

function calculate() {
var houseEl = document.getElementById('houseType'),
nightEl = document.getElementById('nightsCount'),
resultEl = document.getElementById('result');

if (houseEl.selectedIndex < 0 || parseInt(nightEl.value) < 0) {
resultEl.innerHTML = 'n/a';
return;
}
resultEl.innerHTML = parseInt(houseEl.options[houseEl.selectedIndex].value) * parseInt(nightEl.value);
}

window.addEventListener('load', function() {
document.getElementById('btnCalculate').addEventListener('click', calculate);
});
<select id="houseType">
<option value="0">None</option>
<option value="100">House 1</option>
<option value="150">House 2</option>
</select>
<input type="number" min="1" value="1" id="nightsCount" />
<button type="button" id="btnCalculate">Calculate</button>
<div>
The total amount for your stay would be <span id="result"></span> €
</div>

关于javascript - 在 Javascript 中使用多个选项进行计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34601813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com