JavaScript does not check for blank fields

1

Good Night, I have a problem with my JS code, I ask him to check if the fields are empty, but when I execute the function with the empty field, it does not deal with it, it simply ignores the if's, validate, but what I think are examples very similar to what I did

Follow the code in Js and below the HTML

function calculaBask(){

var numA = parseFloat(document.getElementById('a').value),
    numB = parseFloat(document.getElementById('b').value),
    numC = parseFloat(document.getElementById('c').value),
    delta = null,
    x1 = null, x2 = null;

/* TRATATIVAS */

//ver se nao esta vindo numeros nulos
if(numA == '' || numA == null){

    alert("Digite um numero valido para continuar.");
    return false;
}

if(numB == '' || numB == null){

    alert("Digite um numero valido para continuar.");
    return false;
}

if(numC == '' || numC == null){

    alert("Digite um numero valido para continuar.");
    return false;
}

//recebendo o valor de delta
delta = numB * numB - 4 * numA * numC;

//pegando a raiz de delta
raizDelta = Math.sqrt(delta);

//Calculando primeira raiz
x1 = (-numB + raizDelta) / 2 * numA ;

//calculando segunda raiz
x2 = (-numB - raizDelta) / 2 * numA;

document.getElementById('raiz1').value = x1;
document.getElementById('raiz2').value = x2;
document.getElementById('bd').value = delta;

}
<header class="container">

        <h1 style="text-align:center;">Calcule Baskhara</h1>

    </header>

    <section class="container box-space secao-input">

        <label>Digite A:
            <input id="a" type="text" placeholder="">
        </label>

        <label>Digite B:
            <input id="b" type="text" placeholder="">
        </label>

        <label>Digite C: 
            <input id="c" type="text" placeholder="">
        </label>

    </section>

    <div class="container box-space results">
        <label class="label-rs">Raiz 1:
            <input id="raiz1" type="text">
        </label>
        <label class="label-rs">Raiz 2:
            <input id="raiz2" type="text">
        </label>
        <label class="label-rs">Binomio discriminante:
            <input id="bd" type="text">
        </label>
        <button onclick="calculaBask()" id="botao">Calcular</button>
    </div>

    <script src="js/script.js"></script>
    
asked by anonymous 14.01.2018 / 05:10

1 answer

2

When you use parseFloat() and the field is empty (which at first is what you are trying to verify), it returns the string NaN ( not a number is not a number ). With this your if validates the variables because they are no longer empty.

If the field is empty or is not a number, the code below will return NaN :

parseFloat(document.getElementById('a').value);

Solution: Change all conditions in if s by isNaN() :

if(!(numA) == '' || numA == null){

for

if(isNaN(numA)){

And so on. Click here if you want to know more about isNaN() .

    
14.01.2018 / 05:30