establecer como valor 0 si el input esta vacio

publicado por: Anonymous

estoy haciendo una calculadora en la cual rellenas los campos y hace las operaciones, pero como hago para que, si el input no tiene ningun valor, javascript lo interprete como 0?

_x000D_

_x000D_

var button = document.getElementsByTagName("input")[2];_x000D_
var input1 = document.getElementsByTagName("input")[1];_x000D_
var input2 = document.getElementsByTagName("input")[0];_x000D_
_x000D_
_x000D_
button.addEventListener("click", function(){_x000D_
  console.log(input1.valueAsNumber + input2.valueAsNumber);_x000D_
});

_x000D_

<!DOCTYPE html>_x000D_
<html lang="es">_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
    <meta http-equiv="X-UA-Compatible" content="ie=edge">_x000D_
    <link rel="stylesheet" href="./css/index.css">_x000D_
    <title>Calculadoras</title>_x000D_
</head>_x000D_
<body>_x000D_
        <form action="">_x000D_
                <input type="number" step="0.001">_x000D_
                <input type="number" step="0.001">_x000D_
                <input type="submit" value="sumar">_x000D_
        </form>_x000D_
</body>_x000D_
<script src="./JavaScript/index.js"></script>_x000D_
</html>

_x000D_

_x000D_

_x000D_

solución

Lo que tenés que hacer es reconocer en el evento submit() el input y en caso de estar vacío, reemplazarlo por 0. Podés consultar si es un número mediante Number.isNaN().

_x000D_

_x000D_

var input1 = document.getElementsByTagName("input")[1];_x000D_
var input2 = document.getElementsByTagName("input")[0];_x000D_
var form = document.getElementById('formulario');_x000D_
_x000D_
form.addEventListener('submit', function(e) {_x000D_
  if (Number.isNaN(input1.valueAsNumber)) {_x000D_
    input1.value = 0;_x000D_
  }_x000D_
  if (Number.isNaN(input2.valueAsNumber)) {_x000D_
    input2.value = 0;_x000D_
  }_x000D_
  console.log(input1.valueAsNumber + input2.valueAsNumber);_x000D_
  _x000D_
  //prevengo que se submitee, sólo para el ejemplo_x000D_
  e.preventDefault();_x000D_
})

_x000D_

<!DOCTYPE html>_x000D_
<html lang="es">_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
    <meta http-equiv="X-UA-Compatible" content="ie=edge">_x000D_
    <link rel="stylesheet" href="./css/index.css">_x000D_
    <title>Calculadoras</title>_x000D_
</head>_x000D_
<body>_x000D_
        <form id="formulario" action="">_x000D_
                <input type="number" step="0.001">_x000D_
                <input type="number" step="0.001">_x000D_
                <input type="submit" value="sumar">_x000D_
        </form>_x000D_
</body>_x000D_
<script src="./JavaScript/index.js"></script>_x000D_
</html>

_x000D_

_x000D_

_x000D_

Respondido por: Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *