NaN Result Instead Of Percentage

I created the following HTML document with some checkboxes to be ticked off. There is a running tally etc at the bottom of the form as the checkboxes are ticked off.

The problem starts when I try to calculate the score percentage by doing a calculation to the effect of ( score / total the amount of checkboxes, I get a NaN Error. I thought the Nan error would easily be solved by just using the ParseInt feature in JScript, but still to no avail and I continue to struggle.

I am new to Javascript and programming in general. I read and read but somehow things often falls down when it comes to the practical parts. I’ve included the codes. Also, I am not sure whether I am using the right calculation to obtain an accurate percentage due to the ‘NaN’ result instead of a percentage one. The model I usually use in Excel is (score gain / by the total possible amount) The codes are below. I would be grateful for any help received, and thank in advance anyone who are able to offer their help.

<!DOCTYPE html>
<!-- https://www.sitepoint.com/community/t/count-and-show-total-number-of-checkboxes-selected-by-user/302972/4 -->
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

</head>
  <body onload="toTalQuestions()">
  <header>
  <h1></h1>
  <h2>Tick The Boxes Of Streets Known To The Interviewee</h2>
  <h3>Street list: Test 1</h3>
  <h3>See Bottom Of List For Score Tally etc</h3>
 <div>
 <input type="button" id="tick-all-btn" onclick="checkAll2()" class="btn btn-link" value="Tick All Answers">
 <input type="button" onclick="uncheckAll2()" class="btn btn-link" value="Reset Test">
 </div>
 </header>

<div id="wrapper">
<div id="q-wrapper">
<form>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">Price St : Bristol Rd</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">Byard Rd : Bristol Rd</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">Bull Lane : Longsmith St</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">Bell Lane : Brunswick Rd</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">Badger Close : The Richmonds Rd</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">Constitution Walk : Bell Lane</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">St Kilda Parade: Station Rd/Russell St</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">Lacca Cl : Redwind Way</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">Matson Pl : Hatherley Rd</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">Hill Hay Rd : Matson Avenue</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">Quenney Close : Hill Hay Rd/Munsley Grove</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">Orchard Rd : Nine Elms Rd</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">St Luke St : Southgate St</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">George St : Station Approach</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">Escort Close : Escort Rd</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">Chamwells Ave : Oxstalls Way/Flower Way</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">South Close : Chamwell Ave</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">Flower Way : Oxstalls Way/Chamwell Ave/Chamwell Walk</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">The Avenue : Church Rd (Longlevens)</label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">Somerset Pl : Southgate St<label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">Madleaze Rd : Bristol Rd<label><br>
<input type="checkbox" class="check2" name="street" /><label class="q-texts">St Paul’s Parade : Stroud Rd (By Shops & opposite MOT Garage)</label><br>




</form>
</div>

<div id="result">Score = <span id="selected">0</span></div>  <div id="notchecked">Remaing Checkboxes/Not Ticked = <span id="unselected"></span></div> 
<!-- Counting only worked after JS code was moved from the 'head' tag to the bottom of the body tag -->
<div id="num-of-questions">Total Number Of Checkboxes = <span id="totalquestions"></span></div>
<div><strong>Score Percentage</strong> <span id="score-perc" style="color: green; font-size: 1.5em;"></span> <strong>%</strong></div>
<div id="perScoreDiv">



</div>

<script>



// Count Checked
const selectedElm = document.getElementById('selected');

function showChecked(){
  selectedElm.innerHTML = document.querySelectorAll('input[name=street]:checked').length;
}

document.querySelectorAll("input[name=street]").forEach(i=>{
 i.onclick = () => showChecked();
});



// Reset test and Check all checkboxes

//v2 Tick all Checkboxes
function checkAll2() {
  var inputs = document.querySelectorAll('.check2');
  for(var i = 0; i < inputs.length; i++) {
    inputs[i].checked = true;
  }
}

// Untick All Checkboxes
function uncheckAll2() {
  var inputs = document.querySelectorAll('.check2');
  for(var i = 0; i < inputs.length; i++) {
    inputs[i].checked = false;
  }
}


// Count Unticked boxes
$(function () {
    $("input:checkbox").on("change", function () {
        var lenghtOfUnchecked = $('input:checkbox:not(:checked)').length;

        var unticked = document.getElementById('unselected').innerHTML = lenghtOfUnchecked;

    });
});	

// Amount Of Checkboxe Questions
function toTalQuestions() {
  var toTalQuestions = document.getElementsByName('street').length;
  document.getElementById('totalquestions').innerHTML = toTalQuestions;
}





// code doesn't work: Keep getting NaN

  var totalqs = parseInt(document.getElementById("totalquestions").value);
  var correct = parseInt(document.getElementById("selected").value);

  var convertNan = parseInt(totalqs);
  var convertNan2 = parseInt(correct);

    percentsavings = ((toTalQuestions - selectedElm) / toTalQuestions) * 100;
    document.getElementById("score-perc").innerHTML = Math.round(percentsavings*100)/100;



 var showperc = document.getElementById("score-perc").innerHTML = ((totalqs - correct) * totalqs);





 </script>


</body>
</html>

you have jquery cdn but doesn’t look like you’ve used it much, if you change your .value to .innerText it should work so like this…

   function percentage() {
        var totalqs = document.getElementById('totalquestions').innerText
        var correct =  document.getElementById('selected').innerText
        percentsavings = ((totalqs - correct) / totalqs) * 100;
        document.getElementById("score-perc").innerHTML = Math.round(percentsavings * 100) / 100;

      }

and then call the function from inside the showChecked() function
hope this helps :slightly_smiling_face:


        var totalqs = $("#totalquestions").text()
        var correct = $("#selected").text() 

or for jquery

Thanks a million for your assistant. I’ve been away for a while, so please excuse my lack of promptness in replying.

Your function worked nicely. I had to adjust the “percentsavings” syntax by omitting “/ totalqs) * 100;” from the last part of the syntax and also omitted “/ 100;” from the last line to stop the percentage being shown in decimal equivalent

I haven’t utilised the Jquery yet, because as said before. I am getting familiar and experimenting with JScript. It’s a minefield for me at the moment. I will try to visit here more to help with my learning. I’ve over read too much on JS. I need to do more active projects and experiment to bolster my learning.

Thanks once for help

Thanks a million for your assistant. I’ve been away for a while, so please excuse my lack of promptness in replying.

Your function worked nicely. I had to adjust the “percentsavings” syntax by omitting “/ totalqs) * 100;” from the last part of the syntax and also omitted “/ 100;” from the last line to stop the percentage being shown in decimal equivalent

I haven’t utilised the Jquery yet, because as said before. I am getting familiar and experimenting with JScript. It’s a minefield for me at the moment. I will try to visit here more often to help with my learning. I’ve over read too much on JS. I need to do more active projects and experiment to bolster my learning.

Thanks once more for help

1 Like