Empty input can not receive zero value

4

I have a form with more or less 5 inputs , at any given time any of these inputs will be worthless, and I want to find out the lowest value between them, but whenever it has one or more empty inputs 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 whenever it has a input empty one of the locations of the string receives zero and the

Math.min();

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

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

    
asked by anonymous 10.11.2016 / 12:21

4 answers

4

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

  • empty
  • NaN
  • undefined
  • blanks

In this way the unfilled inputs will not be considered when the minimum is reached.

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 for Math.min.apply

    
10.11.2016 / 12:35
1

See if the code below helps you.

  • I get the DOM button
  • I add an event of click that:
    • I get all the inputs
    • Since the return of document.querySelectorAll() is NodeList no I can use array functions on it as .map , .filter and .reduce , so I create a new array and populate it by iterating NodeList
    • During the iteration I take advantage of and do parseFloat since the values of inputs comes as string
    • I make a .filter which returns only the number greater than zero and not equal to NaN
    • I call Math.min using .apply because by default Math.min does not accept an array as a parameter, N numbers as parameters. Then 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 entered as common parameters of the function, not in array format
    • I check if the number returned from Math.min is finite with isFinite because if the array goes empty to Math.min it returns a Infinity
    • Then just alert a message with the smallest number or ask to enter at least one number to not answer Infinity as the least number

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>
    
10.11.2016 / 13:19
1

Following the code Lucas, function verificar of it is without restarting variable it is necessary to zero the value to apply restart, and follow the code below it is 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>

History (Luke): link

    
10.11.2016 / 13:25
1

As you said, you are using a jQuery mask to format the value and add R$ , so you should be using jQuery MaskMoney .

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

In the example below, if you do not enter any value, 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><scriptsrc="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" />
    
10.11.2016 / 13:54