Field input result Nan

Asked

Viewed 191 times

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;


};

It’s in the PHP File (<!DOCTYPE html>). Works perfectly.

Value of input passo / by "Step" the value by input quanti_imagens, but is appearing NaN up to the completion of the two input fields.

How do I eliminate that?

  • Include html, elements with the ids "step" and "quanti_images" are inputs?

1 answer

0


Put a ternary on return v; by checking whether the first character of v is a number:

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

Because if the value of v for NaN, the height value will be empty, otherwise return the result of the split 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>

  • GRANDEEE SAM !! Thank you very much !! It worked !! Success. I’m a PHP layman...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.