计算Total Onclick Javascript [英] Calculate Total Onclick Javascript

查看:62
本文介绍了计算Total Onclick Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Javascript,而且我对这门语言还很新。
在我的HTML代码中,我有两个列表。
在第一个选择列表中,您选择您想要的产品
在第二个选择您需要的产品数量。

I am learning Javascript and am still very new to the language. In my HTML code I have two lists. In the first select list you select the product you want In the second you select the amount of product you require.

我试图写一个javascript代码执行以下操作:

I have attempted to write a javascript code which does the following:


  • 获取产品值并将其分配给变量

  • 获取产品的nr并将其分配给变量

  • 将产品值乘以产品编号

  • 当用户点击提交显示时一个警告框,总计

  • Get the product value and assign it to a variable
  • Get the nr of product and assign it to a variable
  • Multiply the product value with the number of product
  • When the user clicks submit display an alert box with the total

但是当用户点击提交按钮时,我的代码无效我收到消息NaN而不是总金额变量
的结果请你看看我的代码并告诉我我做错了什么

However my code is not working when the user click the submit button I get the message NaN instead of the result of the total amount variable Please can you have a look at my code and tell me what am I doing wrong

<script type="text/javascript">
function calc()
{
   var total;
   var fruitOrVeg;
   var nrOfFruit;

   course = document.getElementsByName("fruitOrVeg.course.value")
   nrOfFruit = document.getElementsByName("nrOfFruit")

   total = fruitOrVeg * nrOfFruit;

   window.alert(total)
}
</script>


推荐答案

您将值作为字符串(而不是数字) ),你没有使用fruitOrVeg。另外(后来注意到/新评论)你正在使用名称,你应该真正使用ID来获取你希望javascript直接和具体地获取数据的元素,然后相应地更新你的js。试试这个:

You are taking the values as strings (rather than numbers), and you weren't using "fruitOrVeg". Also (noticed later/ new comments) you are using names when you should really use ID's for elements you want javascript to get data from directly and specifically, and then update your js accordingly. Try this:

function calc() {
    var fruitOrVeg = Number(document.getElementsById("fruitOrVeg").value);
    var nrOfFruit = Number(document.getElementsById("nrOfFruit").value);

    var total = fruitOrVeg * nrOfFruit;

    window.alert(total)
}

这篇关于计算Total Onclick Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆