简体   繁体   English

带单选按钮选项的Javascript价格计算器

[英]Javascript Price Calculator with Radio Button Options

I'm trying to write a very simple price calculator for a client. 我正在尝试为客户编写一个非常简单的价格计算器。 The want the user to be able to enter their width and length in inches and then choose a product from a group of radio buttons to determine the price. 希望用户能够输入以英寸为单位的宽度和长度,然后从一组单选按钮中选择一种产品来确定价格。 the final calculation will be the width x length x price. 最后的计算将是宽度x长度x价格。 I can get the script to calculate the width and length but I'm not sure how to set the var for the price from the radio button selected. 我可以获取脚本来计算宽度和长度,但是我不确定如何通过选中的单选按钮设置价格的var。 Thanks in advance for anyone that can help with this. 在此先感谢您可以提供帮助的任何人。 I would also like to limit the result to only 2 decimal places. 我还想将结果限制为仅两位小数。 Code is below. 代码如下。

<html>
<head>
<title>Calculator</title>
  <script type="text/javascript">
  //calculator
  function cal() {
  var x=document.form.length.value
  var y=document.form.width.value

  var a=x*y 
  var p=document.form.radio.value
  var total=a*p 
document.form.total.value=total;
}
</script>
</head>
<body>

<h3>Project cost calculator:</h3>
<form action="" name="form">
  <p><input type="text" name="length" size="4" /> 
  Enter the length of your banner in inches.<br />
  <input type="text" name="width" size="4" /> 
  Enter the width of your banner in inches.</p>
  <p>
<input type="radio" name="radio" id="paper" value="0.0625">
paper</label>
<input type="radio" name="radio" id="vinyl" value="0.08333333">
<label for="product">vinyl</label>
  </p>
<p><b>Click this button to calculate the approximate cost of your project:</b><br />
  <input type="button" name="money" value="calculate" onclick="cal()" /></p>

  <p> <input type="text" name="total" size="6" /></p>
</form>
</body>
</html>

Replace your code 替换您的代码

var p=document.form.radio.value

with

var p=document.querySelector('input[name = "radio"]:checked').value

UPDATED: the above code doesn't work in IE, so, the following code should be used 更新:以上代码在IE中不起作用,因此,应使用以下代码

if( document.getElementById("paper").checked == true ){
    var p=document.getElementById("paper").value;
}
else{
    var p=document.getElementById("vinyl").value;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM