Empty input cannot receive zero

Asked

Viewed 1,757 times

4

I have a form with more or less 5 inputs, at any given time inputs will be worthless, and I want to find out what the lowest value between them, but whenever there is one or more inputs voids it returns the value 0 and indicates that this is the smallest number :(

With the inputs I am forming a string with

document.querySelectorAll("input").value;

Receiving the values of input, but every time you have a input empty one of the string locations takes zero and the

Math.min();

calculates this value as the smallest value in the string...

There is a way to ignore the empty input and not put it in the string? or something similar?

  • You could put the html of your inputs?

  • Actually the inputs only have the class I’m using in css, I didn’t put anything else

  • They are all type=text?

  • in fact it is number, this receiving numbers, real values, this with the mask of jquery to catch the comma and the R$ automatically

4 answers

4


You can iterate the input values, and the condition if(item.value) returns true if input is not:

  • emptiness
  • Nan
  • Undefined
  • blanks

Thus unfilled inputs will not be considered at the time of obtaining the minimum.

var inputs = document.querySelectorAll("input"); // obtem todos os inputs
var valores = []; // vetor para armanezar somente os valores. Esse vetor será usado para obter o minimo entre um conjunto de valores

// funcao que será chamada pelo botão verificar
function verificar(){
  // forEach itera os inputs do formulario
  inputs.forEach(item =>{  
    if (item.value) // se o valor do input for valido (não vazio, nem espacos em branco, nem NaN, etc
      valores.push(parseFloat(item.value)); // empilha (adiciona) na lista de valores
  });
  console.log(Math.min.apply(null, valores)); //usamos a função Math min para obter o menor valor de um conjunto de valores
}
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<button onclick="verificar()">Verificar</button>

Some documentation of Math.min.apply

  • Thank you for the answer boy, but some things you used there were out of my knowledge... is in the function "check" that you put the condition of the input? pq after I get the input values, it goes through a function that does some calculations, and then I show the lowest possible result, is a beer price calculator actually... it calculates the lowest price per "ml" and the result of which beer is cheaper (by size and price)

  • Oops, you edited it,...

  • It hasn’t worked out yet. the two variables that you used at first I did the same but with other name, what I did was copy this your function and change the name of the variables in the middle of the function, and did not function :/

  • If you can create a Fiddle with the relevant parts of your code it’s easy to help. https://jsfiddle.net/

  • I made a codepen... take a look but I don’t know if it’ll help..codepen

  • [Jsfiddle] (https://jsfiddle.net/ajb02qdf/)

  • Lucas, this appearing Infinity by avoiding value error is fixes alert(menorValor!='Infinity'?menorValor:0);

  • Thank you @Kingrider, I put the suggested validation: http://codepen.io/anon/pen/VmeYxY.

  • It worked!! Thanks @Lucascosta... what’s the secret?? parseFloat ???

Show 4 more comments

1

Following the code Lucas, function verificar of it is without restarting variable it is necessary to reset the value to apply restart, and follows the code below this corrected.

function verificar(){
  var campo = document.querySelectorAll("input");
  var valores = [];
  campo.forEach(item =>{
      if (!item.value) item.value = 0;
      valores.push(parseFloat(item.value));
  });
  console.log(valores.sort()[0]);
  //ou pode ser abaixo lucas postaram
  //console.log(Math.min.apply(null, valores));
}
<input type="text"/><br/>
<input type="text"/><br/>
<input type="text"/><br/>
<button onclick="verificar()">Verificar</button>

Historical (Lucas): http://i.imgur.com/xDj9UkB.png

1

as you said is wearing a mask jQuery to format the value and add the R$, then you must be using the jQuery MaskMoney.

So the first thing to do is to use the method .maskMoney('unmasked') get all the valores, then perform a filter (you can use the Array.prototype.filter for this) to ignore the values below zero, finally call the Math.min.

In the example below, if you do not enter any value, the Math.min will return infinito.

var inputsMoney = $("input[data-money]");
inputsMoney.maskMoney();

$("#btMenorValor").on("click", function () {
  var valores = inputsMoney.maskMoney('unmasked');
  var valores = [].filter.call(valores, function (numero, indice) {
    return numero > 0;
  })
  console.log(Math.min.apply(null, valores));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>

<div>
  <label>
    Valor: 
    <input type="text" data-money data-affixes-stay="true" data-prefix="R$ " data-thousands="." data-decimal="," />
  </label>
</div>
<div>
  <label>
    Valor: 
    <input type="text" data-money data-affixes-stay="true" data-prefix="R$ " data-thousands="." data-decimal="," />
  </label>
</div>
<div>
  <label>
    Valor: 
    <input type="text" data-money data-affixes-stay="true" data-prefix="R$ " data-thousands="." data-decimal="," />
  </label>
</div>
<div>
  <label>
    Valor: 
    <input type="text" data-money data-affixes-stay="true" data-prefix="R$ " data-thousands="." data-decimal="," />
  </label>
</div>
<div>
  <label>
    Valor: 
    <input type="text" data-money data-affixes-stay="true" data-prefix="R$ " data-thousands="." data-decimal="," />
  </label>
</div>
<input id="btMenorValor" type="button" value="Menor Valor" />

1

See if the code below helps you.

  • I take the DOM button
  • I add an event from click that:
    • I take all inputs
    • As the return of document.querySelectorAll() is aNodeList nay I can use array functions in it like .map, .filter and .reduce, then create a new array and populate it by iterating the NodeList
    • During the iteration I already take advantage and do the parseFloat for the values of inputs comes as string
    • I make a .filter that returns me only the number greater than zero and different from NaN
    • I call Math.min using the .apply because by default the Math.min does not accept an array as parameter, N numbers as parameters. So the .apply lets me pass the scope of the function as the first parameter and in the second parameter I give an array that will be inserted as common function parameters, not in array format
    • I confirm if the number returned from Math.min is finite with the isFinite in case the array is empty for the Math.min he returns a Infinity
    • Then just alert a message with the smallest number or ask to inform at least one number not to reply Infinity as fewer

var button = document.querySelector('button');

button.addEventListener('click', function() {

  var inputs = document.querySelectorAll('input[type=number]');
  var valores = [];

	for(var i = 0; i < inputs.length; i++) {
      valores.push(parseFloat(inputs[i].value));
  }
  
  valores = valores.filter(function(valor) {
  	return !isNaN(valor) && valor > 0;
  });
  
  var menorNumero = Math.min.apply({}, valores);
  
	var mensagem = 'Informe pelo menos um número';
  
  if(isFinite(menorNumero)) {
  	mensagem = 'O menor número é ' + menorNumero;
  }
  
  alert(mensagem);

});
<input type="number" /> <br />
<input type="number" /> <br />
<input type="number" /> <br />

<button type="button">
  Pegar menor número
</button>

Browser other questions tagged

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