invincibleme invincibleme - 3 months ago 19
Javascript Question

Forma validation

I have an html form that has 6 input boxes that should add up to 100. If they don't add put to 100 or there are inputs left empty, alerts should appear when the button is clicked. So far I can get the alert if the total isn't right, but not for an empty field.

HTML



<fieldset>

<input type="text" name="qty" oninput="findTotal()" id="qty1" class="hvr-pop" required/>

<input type="text" name="qty" oninput="findTotal()" id="qty2" class="hvr-pop" required/>

<input type="text" name="qty" oninput="findTotal()" id="qty3" class="hvr-pop" required/>

<input type="text" name="qty" oninput="findTotal()" id="qty4" class="hvr-pop" required/>

<input type="text" name="qty" oninput="findTotal()" id="qty5" class="hvr-pop" required/>

<input type="text" name="qty" oninput="findTotal()" id="qty6" class="hvr-pop" required/>

</fieldset>

<button type="button" class="weightageButton" onclick="validateTotal()">TOTAL WEIGHTAGE</button>
<output type="text" name="total" id="total" class="hvr-pop" readonly value="Must total 100"></output>


Javascript

for(var i=0; i<arr.length;i++){
if(parseInt(arr[i].value) === null || score > 100 || score < 100) {

alert("Please make sure each weightage is filled in and the total adds up to 100.");
$('#form1').find('input').val('');
$('#form1').find('#total').val('');
return false;
}



}
}

Answer

The thing is that parseInt() for empty string returns NaN, not a NULL. You should replace current check to this:

    if (isNaN(parseInt(arr[i].value)) || ... ) { ... }