Field input result NaN

1

I have the following code:

<script type="text/javascript">
function id(el) {
  return document.getElementById( el );
}
function altura( un, quanti_imagens ) {
  return parseFloat(un.replace(',', '.'), 10) / parseFloat(quanti_imagens.replace(',', '.'), 10);
}
window.onload = function() {
  id('passo').addEventListener('keyup', function() {
    var result = altura( this.value , id('quanti_imagens').value );
    id('altura').value = String(result.toFixed(2)).formatMoney();
  });

  id('quanti_imagens').addEventListener('keyup', function(){
    var result = altura( id('passo').value , this.value );
    id('altura').value = String(result.toFixed(2)).formatMoney();
  });
}

String.prototype.formatMoney = function() {
  var v = this;

  if(v.indexOf('.') === -1) {
    v = v.replace(/([\d]+)/, "$1,00");
  }

  v = v.replace(/([\d]+)\.([\d]{1})$/, "$1,$20");
  v = v.replace(/([\d]+)\.([\d]{2})$/, "$1,$2");
  v = v.replace(/([\d]+)([\d]{3}),([\d]{2})$/, "$1.$2,$3");

  return v;


};

You are in the PHP File ( <!DOCTYPE html> ). It works perfectly.

Value of input passo / by "Step" the value of the input quanti_imagens , but it is appearing NaN until the two input fields .

How do I delete this?

    
asked by anonymous 27.07.2018 / 20:03

1 answer

0

Put a ternary in return v; by checking if the first character of v is a number:

return isNaN(v[0]) ? '' : v;

Because if the value of v is NaN , the height value will be empty, otherwise return the result of the division in v .

Example:

function id(el) {
  return document.getElementById( el );
}

function altura( un, quanti_imagens ) {
  return parseFloat(un.replace(',', '.'), 10) / parseFloat(quanti_imagens.replace(',', '.'), 10);
}

window.onload = function() {
  id('passo').addEventListener('keyup', function() {
    var result = altura( this.value , id('quanti_imagens').value );
    id('altura').value = String(result.toFixed(2)).formatMoney();
  });

  id('quanti_imagens').addEventListener('keyup', function(){
    var result = altura( id('passo').value , this.value );
    id('altura').value = String(result.toFixed(2)).formatMoney();
  });
}

String.prototype.formatMoney = function() {
  var v = this;

  if(v.indexOf('.') === -1) {
    v = v.replace(/([\d]+)/, "$1,00");
  }

  v = v.replace(/([\d]+)\.([\d]{1})$/, "$1,$20");
  v = v.replace(/([\d]+)\.([\d]{2})$/, "$1,$2");
  v = v.replace(/([\d]+)([\d]{3}),([\d]{2})$/, "$1.$2,$3");

  return isNaN(v[0]) ? '' : v;

};
Passo:
<br>
<input id="passo">
<br>
Quantidade:
<br>
<input id="quanti_imagens">
<br>
Altura:
<br>
<input id="altura" disabled>
    
27.07.2018 / 20:21