简体   繁体   English

如何使用javascript获取两个数字的总和

[英]how can i get total of two numbers using javascript

I'm using this form script to automatically calculate totals. 我正在使用此表单脚本自动计算总计。 Now I need to get that total and print it. 现在,我需要获取总计并打印出来。 Here is my code. 这是我的代码。

 function myFunction() { var x = document.getElementById("frm1"); var txt1 =x.elements[0].value; var txt2 =x.elements[1].value; var total =txt1+txt2; document.getElementById("demo").innerHTML="total is :"+total; } 
 <body> <form id="frm1"> First value : <input type="text" name="first"><br> Second Value : <input type="text" name="second"><br> </form> <p id="demo"></p> <button onclick="myFunction()"> ADD </button> </body> 

It doesn't really say, but I'm guessing you're talking about numbers, if so parse the string values as numbers before you add them up 它并没有真正说出,但是我猜您在谈论数字,如果在将它们加起来之前将字符串值解析为数字

function myFunction() {
    var x     = document.getElementById("frm1");
    var txt1  = parseFloat( x.elements[0].value );
    var txt2  = parseFloat( x.elements[1].value );
    var total = txt1 + txt2;

    document.getElementById("demo").innerHTML = "total is :"+total;
}

FIDDLE 小提琴

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

相关问题 如何使用javascript获取此集合的总计数ID? - How can i get the total count id of this collection using javascript? 如何使用ejs(嵌入式JavaScript)将两个数字相加? - How can I add two numbers using ejs(Embedded JavaScript)? 如何从数组中减去数字以使总数为 0。我想跳过会使总数为负数的数字 - How can I subtract numbers from an Array to get my total to 0. I want to skip numbers that would make my total a negative 使用javascript从表行的总数中获取最低的两个数字 - Using javascript to take the lowest two numbers from the total of a table row 如何在JavaScript中获取以KM为单位的总距离 - How can i get the total distance in KM in my javascript 我如何使用javascript将数字乘以9的1到1000的数字? - how can i separate the numbers multiple by 9 in 1 to 1000 numbers using javascript? 如何使用 JavaScript 计算购物车中产品的总价格? - How can I calculate the total price of products in a cart using JavaScript? 如何检查两个数字是否以相同的数字开头 Javascript - How can i check if two numbers start with the same digits Javascript Javascript:如何在不转换为数字的情况下添加两个字符串? - Javascript: How can I add two strings without converting into numbers? 如何在Javascript中将一个字符串拆分为两个浮点数? - How can I split a string into two float numbers in Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM