I'm trying to create a form, where the user pick an answer from 0 to 100%; I've 25 questions. A the end, I add the result of each questions and I divide this by the number of questions, 25 in my case. So far, no problem; it works perfectly, I've the average I need.
But I've a problem, if the user decides to not answer at a question. If he answers at 20 questions, I divide by 20, no problem. But the result of my calculation is 'NaN' because some variable doesn't exist...
This solution works for me :
<input type="text" class="q" value="">
<input type="text" class="q" value="">
<input type="text" class="q" value="">
<input type="submit" class="send" value="send">
JS :
$(".send").click(function() {
let answeredCount = 0;
var sum = 0;
$('.q').each(function(){
if(!isNaN(parseInt($(this).val()))){
answeredCount++;
}
sum += Number($(this).val());
});
var result = parseInt(sum/answeredCount);
alert (result);
});