如何使用HTML输入框设置JavaScript变量?

时间:2019-08-17 20:56:25

标签: javascript html

我正在尝试用用户输入编写一个简单的一页计算器脚本。由于缺乏JS知识,我不断遇到问题。我觉得我正在做的事情应该可行并且是正确的,但是显然我在这里缺少一些东西。

我希望HTML输入框为JS函数设置变量。我只是无法弄清楚我在做什么错。

如果我能朝着正确的方向微移,我将不胜感激。

<body>
   <input type="text" id="price"=>Price</input>
   <br>
   <input type="text" id="value"=>Value</input>
   <br>
   <button onclick="sub()">Submit</button>
</body>
<script>      
   function sub() {
           
   var value = document.getElementById("value").value;
   var price = document.getElementById("price").value;
           
   var keep = value * 0.7
   var sell = keep * 0.7
   var profit = sell / 1000 * 6 - price
   var keeprate = price / keep * 1000
   var earned = profit + price
   
   
   
   document.write("Keeping: R$ ");
   document.write(keep);
   document.write("<br>");
   document.write("1k Buy Rate: $");
   document.write(keeprate);
   document.write("<br>");
   document.write("<br>");
   document.write("Selling: R$ ");
   document.write(sell);
   document.write("<br>");
   document.write("1k Buy Rate: ");
   document.write("$6.00");
   document.write("<br>");
   document.write("<br>");
   document.write("Total Cost $");
   document.write(price)
   document.write("<br>");
   document.write("Total Return $");
   document.write(earned)
   document.write("<br>");
   document.write("Net: $");
   document.write(profit);
   }
</script>

1 个答案:

答案 0 :(得分:2)

我认为您的主要问题是函数声明。您没有function sub()

的开合括号

添加一个右括号,以正确声明您的功能。

function sub() {

    code

}