Javascript Addition wont work

泪湿孤枕 提交于 2019-11-29 18:19:53

The value of elements is always a string, so + will result in concatenation, not addition.

Convert from string to number when retrieving the values:

var preciopag = +document.valores.T1.value;
var libras = +document.valores.T2.value;

There I've used +, which will look at the entire string, but you might look at parseFloat which will ignore anything invalid at the end; it depends entirely on what you want to do with semi-valid input.

Demonstration:

var preciopag = "5";   // Simulating document.valores.T1.value
var libras = "10";     // Simulating document.valores.T2.value
var serviciocom = 5.00
var contador1 = 0;
var contador2 = 0;
var tramite = 0;
var enviopty = 0;
var ITBMS = 0;
var Total = preciopag + serviciocom + enviopty + tramite + ITBMS;

snippet.log(Total); // "55000" - wrong

// Instead:
preciopag = +"5";    // Simulating document.valores.T1.value 
libras = +"10";      // Simulating document.valores.T2.value
Total = preciopag + serviciocom + enviopty + tramite + ITBMS;

snippet.log(Total); // "10" - right
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!