set as value 0 if the input is empty

2

I'm doing a calculator in which you fill in the fields and do the operations, but how do I do it so that, if the input has no value, javascript interprets it as 0?

var button = document.getElementsByTagName("input")[2];
var input1 = document.getElementsByTagName("input")[1];
var input2 = document.getElementsByTagName("input")[0];


button.addEventListener("click", function(){
  console.log(input1.valueAsNumber + input2.valueAsNumber);
});
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="./css/index.css">
    <title>Calculadoras</title>
</head>
<body>
        <form action="">
                <input type="number" step="0.001">
                <input type="number" step="0.001">
                <input type="submit" value="sumar">
        </form>
</body>
<script src="./JavaScript/index.js"></script>
</html>
    
asked by Lucho K 14.08.2018 в 21:56
source

6 answers

2

What you have to do is to recognize in the event submit() the input and if it is empty, replace it with 0 . You can check if it is a number using Number.isNaN() .

var input1 = document.getElementsByTagName("input")[1];
var input2 = document.getElementsByTagName("input")[0];
var form = document.getElementById('formulario');

form.addEventListener('submit', function(e) {
  if (Number.isNaN(input1.valueAsNumber)) {
    input1.value = 0;
  }
  if (Number.isNaN(input2.valueAsNumber)) {
    input2.value = 0;
  }
  console.log(input1.valueAsNumber + input2.valueAsNumber);
  
  //prevengo que se submitee, sólo para el ejemplo
  e.preventDefault();
})
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="./css/index.css">
    <title>Calculadoras</title>
</head>
<body>
        <form id="formulario" action="">
                <input type="number" step="0.001">
                <input type="number" step="0.001">
                <input type="submit" value="sumar">
        </form>
</body>
<script src="./JavaScript/index.js"></script>
</html>
    
answered by 14.08.2018 / 23:27
source
1

How should you use the ternary operator? I hope it serves you.

 var button = document.getElementsByTagName("input")[2];


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

var input1 = (document.getElementsByTagName("input")[1].value == "")? 0:document.getElementsByTagName("input")[1].value ;
var input2 = (document.getElementsByTagName("input")[0].value ==  "")? 0:document.getElementsByTagName("input")[0].value;

 
  console.log(input1*1 + input2*1);
});
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="./css/index.css">
    <title>Calculadoras</title>
</head>
<body>
        <form action="">
                <input type="number" step="0.001">
                <input type="number" step="0.001">
                <input type="submit" value="sumar">
        </form>
</body>
<script src="./JavaScript/index.js"></script>
</html>
    
answered by 14.08.2018 в 23:32
1

Basically you need to know if the values entered correspond to valid numbers, and in this case if you leave the input empty NOT A NUMBER , you must validate it with the function isNaN of Javascript

var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
var button = document.getElementById("btn");

button.addEventListener("click", function(e){
  if(isNaN(parseInt(input1.value)) || isNaN(parseInt(input2.value))){
    alert('Ingrese ambos números')
  }
  else{
    alert(parseInt(input1.value) + parseInt(input2.value));    
  }
  e.preventDefault();
});
<form action="">
  <input id="input1" type="number" placeholder="Ingrese un número" step="0.001">
  <input id="input2" type="number" placeholder="Ingrese un número" step="0.001">
  <input id="btn" type="submit" value="sumar">
</form>
<script src="./JavaScript/index.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

If you observe place each element of DOM a id , but it is clearly by own custom; the way you get the values ( getElementsByTagName ) is also valid colleague!

Greetings!

    
answered by 14.08.2018 в 22:46
0

With jQuery you can make it very simple ... like this:

       var input2 =  $("input["+0+"]").val().length;

       if (input2 <= 0) {  
          input2=0;   
        }
    
answered by 14.08.2018 в 22:08
0

only with adding a value 0

var button = document.getElementsByTagName("input")[2];
var input1 = document.getElementsByTagName("input")[1];
var input2 = document.getElementsByTagName("input")[0];


button.addEventListener("click", function(){
  console.log(input1.valueAsNumber + input2.valueAsNumber);
});
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="./css/index.css">
    <title>Calculadoras</title>
</head>
<body>
        <form action="">
                <input type="number" step="0.001" value=0>
                <input type="number" step="0.001" value=0>
                <input type="submit" value="sumar">
        </form>
</body>
<script src="./JavaScript/index.js"></script>
</html>
    
answered by 14.08.2018 в 22:08
-1

null and the empty string are conceptually equal to zero when treated as an entity of type Number. The simplest solution I can think of is:

Assume that the input variable is the HTML element of the input to be checked (you can obtain it with document.querySelector, for example):

var number = Number(input.value)

if (Number.isNaN(number)) {
    // El input en cuestión contenía un valor inválido, como "patata".
} else {
    // El input en cuestión contenía un valor válido. Si input.value es null o "", Number(input.value) es igual a cero. Ahora la variable number contiene el valor deseado.
}
    
answered by 16.08.2018 в 09:52