对于一组多项选择题,我需要得到一个总计。每个选项都分配有一个数值。
如果总数超过50,用户将收到一封电子邮件,通知他们其申请已提交。
到目前为止,我还无法产生总体得分。
我尝试了许多在这里找到的不同解决方案,并尝试应用它们,但是没有一个起作用。对JavaScript来说是相当新的东西,无济于事!
$(":radio").on("change", function() {
var total = 0;
$(":radio:checked").each(function() {
total += Number(this.value);
});
$("#total").text(total);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<form action="">
<li>
<div>
<h3>What age band do you fit into?</h3>
<input class="calc" type="radio" name="radio1" value="25" checked="true">25 - 31<br>
<input class="calc" type="radio" name="radio1" value="25" checked="true">32 - 38<br>
<input class="calc" type="radio" name="radio1" value="25" checked="true">39 - 43<br>
</div>
</li>
<p>Total Score:<span id="total">0</span></p>
</form>
</body>
</html>
答案 0 :(得分:0)
您已将脚本放置在<head>
标记中。将其移到身体下方将正确加载:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form action="">
<li>
<div>
<h3>What age band do you fit into?</h3>
<input
class="calc"
type="radio"
name="radio1"
value="25"
checked="true"
/>25 - 31<br />
<input
class="calc"
type="radio"
name="radio1"
value="25"
checked="true"
/>32 - 38<br />
<input
class="calc"
type="radio"
name="radio1"
value="25"
checked="true"
/>39 - 43<br />
</div>
</li>
<p>Total Score:<span id="total">0</span></p>
</form>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript">
$(":radio").on("change", function() {
var total = 0;
$(":radio:checked").each(function() {
total += Number(this.value);
});
$("#total").text(total);
});
</script>
</html>
答案 1 :(得分:0)
一个简单的例子,我相信您会在这里尝试完成。只需存储您添加的值,然后从总数中减去它,然后再添加一个新值即可。
(function () {
var group = document.forms.myForm.elements.add;
var currentValue = function currentValue () {
for (var i = 0, j = group.length; i < j; i++) {
if (group[i].checked) {
return Number(group[i].value);
}
}
};
var oldValue = currentValue();
var total = document.getElementById('total').firstChild;
var update = function update () {
var current = currentValue();
total.data = Number(total.data) - oldValue + current;
oldValue = current;
};
for (var i = 0, j = group.length; i < j; i++) {
group[i].onchange = update;
}
}());
<form action="" method="get" id="myForm">
<fieldset id="myRadioGroup">
<legend>Which Age Band do You Fit Into?</legend>
<div>
<label> <input type="radio" value="0" name="add" checked> 25 - 31 </label>
</div>
<div>
<label> <input type="radio" value="20" name="add"> 32 - 38 </label>
</div>
<div>
<label> <input type="radio" value="30" name="add"> 39 - 43 </label>
</div>
</fieldset>
</form>
<div id="total">0</div>