jQuery sum of radio fields
Quick survey with score.
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>jQuery Sum of Radio Fields</h1>
<form action="">
<h2>HOW GREEN ARE YOU?</h2>
<p><strong>I walk/bicycle to work/school. </strong><br>
Yes
<input class="calc" type="radio" name="radio1" value="10">
No
<input class="calc" type="radio" name="radio1" value="0">
Sometimes
<input class="calc" type="radio" name="radio1" value="5"></p>
<p><strong>I buy locally grown food. </strong><br>
Yes
<input class="calc" type="radio" name="radio2" value="10">
No
<input class="calc" type="radio" name="radio2" value="0">
Sometimes
<input class="calc" type="radio" name="radio2" value="5"></p>
<p><strong>I recycle. </strong><br>
Yes
<input class="calc" type="radio" name="radio3" value="10">
No
<input class="calc" type="radio" name="radio3" value="0">
Sometimes
<input class="calc" type="radio" name="radio3" value="5"></p>
<p><strong>I compost. </strong><br>
Yes
<input class="calc" type="radio" name="radio4" value="10">
No
<input class="calc" type="radio" name="radio4" value="0">
Sometimes
<input class="calc" type="radio" name="radio4" value="5"></p>
<p>Total Green Score:
<input type="text" name="sum">
</p>
</form>
</body>
</html>
CSS
form {
border:5px solid #9C0;
background-color:#FFC;
padding: 12px;}
input {color: #096; font-weight:bold}
h1,h2, p {margin-bottom:26px}
JavaScript
function calcscore() {
var score = 0;
$(".calc:checked").each(function() {
score += parseInt($(this).val(), 10);
});
$("input[name=sum]").val(score)
}
$().ready(function() {
$(".calc").change(function() {
calcscore()
});
});