简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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