How to validate so that there is no Na in a field?

2

I have the following function that is sent to call when I enter the page, but at that time I still do not have the variables full with values, since they load up to fill a few combos and reload the page.

The first time you enter, the field inputTotal shows NaN I imagine because there is nothing even in the variable, and when you fill a few combos and the page is loaded, it is already shown in value of variable total in my input

function calcularTotal(){


var valor = parseInt($(#inputCalculo1).val());
var valor1 = parseInt($(#inputCalculo2).val());
var valor2 = parseInt($(#inputCalculo3).val());


var total = valor + valor1 + valor2;
document.getElementById("inputTotal").value=total;

}

How can I validate it so that it does not appear in my input the first time it enters the page, but it is shown in blank nothing else, and when filling in the data and loading the page, it already shows the value of the variable

How could I do it?

Is it ok that I do the parseInt ?, the values that I have inputCalculo1, inputCalculo2, y inputCalculo3 are numeric values, and is that if I do not put it in parseInt when doing the sum, do not add them, just put together the numbers

I hope you can support me, thanks

    
asked by Root93 12.09.2018 в 06:27
source

2 answers

3

You must ask if the number isNaN, if it is, change it to something and if not, leave it with its value

let total=Number.NaN;
isNaN(total)? total='algo':total;
console.log(total);
document.getElementById("inputTotal").innerHTML=total;
<div id='inputTotal'></div>
    
answered by 12.09.2018 в 06:36
0

By carrying out a small validation in the assignment of values you ensure that the sum will be made correctly. This can be done by implementing a function in which if the value is not correct, a 0 is returned.

function adaptar ( value ) {
  return !isNaN(value) ? value : 0;
}

function calcularTotal(){

  var valor = parseInt(adaptar($(#inputCalculo1).val()));
  var valor1 = parseInt(adaptar($(#inputCalculo2).val()));
  var valor2 = parseInt(adaptar$(#inputCalculo3).val()));
  var total = valor + valor1 + valor2;
  document.getElementById("inputTotal").value=total;

}
    
answered by 13.09.2018 в 01:06