-2

With the code below I get 'Your score is NaN' and I cannot work out why. The final code will add up all the questions in the quiz.

In the browser I can see that the value of the radio is being correctly picked up and i use parseint to convert it to a number. But clearly something is wrong

Appreciate your help.

<form id="form1" method="post">
<br><strong><label for="benefit1">From the list below select those that are ISO27001 Benefits 
</strong></span></label><br><br>
<input type="checkbox" name="benefit1" value="1" /> Helps you to comply with other regulations</p>
<input type="checkbox" name="benefit2" value="1" /> Keeps confidential information secure</p>
<input type="checkbox" name="benefit3" value="1" /> Protects the company, assets, shareholders and 
directors</p>
<input type="checkbox" name="benefit4" value="1" /> Allows for secure exchange of information</p>
<input type="checkbox" name="benefit5" value="1" /> Manages and minimises risk exposure</p>


<br><input id="Q4PrevBut" type="button" Value="Previous Question">  
    <input id="Q4NextBut" type="button" Value="Next Question">  

</form>

</div>

<div class ="Q5">

<p>Your score is: <span id="grade"></span></p>

<script>

var a1 = parseInt($("input[name='benefit1']:checked").val());

var result = a1;
   
document.getElementById("grade").innerHTML = result;

</script>

</div>
</body>
</html>
DRH09
  • 5
  • 3
  • 2
    Your code is running immediately without waiting for the user to input something. You need to provide an event listener – trincot Aug 18 '20 at 10:47
  • You also need to consider what `$("input[name='benefit1']:checked").val()` will evaluate to if no checkbox is checked. – Dai Aug 18 '20 at 10:48

1 Answers1

0

Your query $("input[name='benefit1']:checked").val() will get input element with name='benefit1' only if it is checked, but your script executes immediately upon loading the page when there is no checkbox which is checked. So this $("input[name='benefit1']:checked") query won't retrieve any elements. My suggestion is to attach onclick event on every checkbox element and call function which handle the event. Something like this: <input type="checkbox" name="benefit1" value="1" onclick="handleCheckbox(this)"/> handleCheckbox function:

function handleCheckbox(checkbox){
   result = parseInt(this.value);
...
}
Bane2000
  • 187
  • 1
  • 9