Checkboxes to create a cost Total in HTML

A student and I are trying to figure out how to use her checkboxes in the Code.org HTML Editor. We want them, when checked, to add to a running total. (Like when custom ordering an item on a website, we want it to tally our total cost at the end of our custom order).

Not sure if we need variables, to use a form, or something else.

Thank you!

  • Andrew Tyler

Hi,

I am not sure if there is an easy way to make this happen. I found this link that shows how to do this using JavaScript. https://stackoverflow.com/questions/28825477/display-total-price-when-checkbox-clicked-in-js
There are several different examples of code online that will do what your student wants but they will not be able to do that in Web Lab. It involves scripting, which web lab does not allow for security reasons. Web lab will only allow static websites.

Karen

Getting the total is very simple; This is very unprofessional but it sets an example.

<!DOCTYPE html>
<html>
<head>
<style>
	#result:before {
    	content:"TOTAL: "
    }
</style>
<script>
function getTotal() {
var list = document.getElementsByClassName("check");
var total=0;
for (var i = 0; i<list.length; i++) {
	if (list[i].checked) {
		total+=Number(list[i].getAttribute("val"))
	}
}

document.getElementById("result").textContent = total;
}
</script></head>
<body>
  <input type="checkbox" class="check" val=10> 10<br>
  <input type="checkbox" class="check" val=20> 20<br>
  <input type="checkbox" class="check" val=30> 30<br>
<button onclick="getTotal()">Calculate</button>
<p id = "result"></p>
</body>
</html>