so I have this code:

function check_total()
   var inputElems = document.getElementsByTagName("input"),
    total = 0;

    for (var i=0; i<inputElems.length; i++) {       
       if (inputElems[i].type == "checkbox"){

document.getElementById('totalInput').innerHTML = total;

Basically, it counts the number of checkboxes in my document.

I would like to have the result (total) displayed in the header of my HTML.

I tried this so far, but didn’t work:

<span id='totalInput'>default</span>


There is a few things you are missing in your code snippet.

First of all, you will need to move your “total” variable outside of the function. By becoming a global variable, you will be able to use it later in your code.

Secondly, you need to actually trigger this function so that it executes and updates the total variable. You can do this with


right before the document.getElementById… line

Finally, you could simplify this by using document.querySelectorAll() function. This will return you an array of all matching elements and you can simply use this as part of your .innerHTML . By using this, you can replace all of your code by:

document.getElementById('totalInput').innerText = document.querySelectorAll("input[type=checkbox]").length;

Finally, on a side note, you should probably use .innerText instead of .innerHTML. Using innerHTML is always dangerous as someone could inject some javascript here. In this case, since you don’t want to display actual HTML, just use .innerText which does the same thing but with text instead of HTML.

Here is a working example:,js,output