简体   繁体   English

将值从html传递到javascript

[英]Passing values from html to javascript

So the user enters in the weight of apples that they want. 因此,用户输入了他们想要的苹果的重量。 Then the total is calculated using a standard formula and then it is printed out. 然后使用标准公式计算总数,然后将其打印出来。 I cant seem to get the output to work. 我似乎无法使输出正常工作。 Thanks in advance for the help. 先谢谢您的帮助。

         <!DOCTYPE html>
<html>
    <head>

    <script type= "text/javascript">
    function output(){
    var total=0,nb1=0,nb2=0,nb3=0; 

    nb1=document.orderForm.apple.value;
    nb2=document.orderForm.orange.value;
    nb3=document.orderForm.banana.value;
    total=(nb1*0.65)+(nb2*0.50)+(nb3*0.73);
    document.writeln("The total price for all your fruit is "+ total);
    }   
    </script>
    </head>


    <body>
        <form>
        <label>
        Apples:
        <input type ="text" name="apple" size="3"   >       
        <br>
        <br>
        Orange:
        <input type ="text" name="orange" size="3">     
        <br>
        <br>
        Banana:
        <input type ="text" name="banana" size="3">
        <br>
        <br>

        <button 
        type="button" onClick="orderFrom()" value = "Submit" > Submit
        </button>

        <input type="reset">
        </label>
        </form>
    </body>
</html>
  1. Don't use inline JS like onClick="orderFrom()", 不要使用像onClick =“ orderFrom()”这样的内联JS,
  2. Set id="orderForm" to your <form> id="orderForm"为您的<form>
  3. Set id="btn" to your <button> id="btn"为您的<button>
  4. Change your js for something like this 改变你的js这样的事情

     var form = document.getElementById('orderForm'), btn = document.getElementById('btn'), inputs = form.getElementsByTagName('input'); btn.addEventListener('click', function(e) { e.preventDefault(); var total = parseFloat(inputs[0].value)*0.65 + parseFloat(inputs[1].value)*0.50 + parseFloat(inputs[2].value)*0.73; // print result -> this is bad code, better to use element.innerHTML = total document.writeln("The total price for all your fruit is " + total.toFixed(2)); }, false); 

JSFiddle -> https://jsfiddle.net/rzb44767/1/ JSFiddle-> https://jsfiddle.net/rzb44767/1/

只是为了优化代码,您是否需要为水果数分配变量?,您只使用一次,因此您可以console.log()直接将它们乘以价格,例如console.log(document.orderForm.apple.value*0.65 + ....) ,此外,您还必须将代码放在HTML之后,否则它将在HTML加载之前加载并运行,并且找不到任何要操作的东西,还可以包装window.onload ()将您的代码保留在底部(我不建议这样做!)>这就是为什么您的代码将无法运行!

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

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