【发布时间】:2016-07-13 01:42:23
【问题描述】:
我已经搜索了论坛,但我似乎无法找到解决这个小问题的方法。
所以我有这个表格,我有 10 个单选按钮组,每个组当然具有相同的名称。我需要做的是遍历十个组中的每一个,并在所有这些组都未选中时执行一个功能,但我似乎无法找到解决方案。到目前为止,我已经完成了 10 次代码重复,我知道这不是一个好主意。我相信也有更好的方法来做到这一点。
到目前为止我所拥有的是:
var drivingCheck = document.getElementById('index-form').Driving;
for (var i = 0; i < drivingCheck.length; i++) {
if (drivingCheck[i].checked == true) {
break;
} else {
totalCount -= 5;
console.log(totalCount);
break;
}
}
var sleepCheck = document.getElementById('index-form').Sleep;
for (var i = 0; i < sleepCheck.length; i++) {
if (sleepCheck[i].checked == true) {
break;
} else {
totalCount -= 5;
console.log(totalCount);
break;
}
}
这是两个单选按钮组,我有十个。我怎样才能做到这一点而不重复自己这么多次? & 当前代码的问题是,如果选中除第一个元素之外的任何单选按钮,则代码执行“false”操作,只有在组的所有元素上的“.checked”为 false 时才应执行该操作。
编辑
此更新现在使代码仅在未检查所有字段时才执行操作,但我仍然重复代码太多次:
var recreationCheck = document.getElementById('index-form').Recreation;
for (var i = 0; i < recreationCheck.length; i++) {
if (recreationCheck[i].checked == true) {
break;
} else if (recreationCheck[0].checked && recreationCheck[2].checked && recreationCheck[3].checked && recreationCheck[4].checked && recreationCheck[5].checked == false) {
totalCount -= 5;
console.log(totalCount);
break;
}
}
这是两个组的 HTML:
<h3>9: Sleep Per Night</h3>
<div class="options">
<input name="Sleep" type="radio" value="0" class="radioCheckBtn">I can sleep with no problem
<input name="Sleep" type="radio" value="1" class="radioCheckBtn">My sleeping is a slight problem (only 1 hour lost sleep)
<input name="Sleep" type="radio" value="2" class="radioCheckBtn">My sleeping is a mildly problem (1 to 2 hours lost sleep
<input name="Sleep" type="radio" value="3" class="radioCheckBtn">My sleeping is a moderate problem (2 to 3 hours lost sleep)
<input name="Sleep" type="radio" value="4" class="radioCheckBtn">My sleeping is a great problem (3 to 5 hours lost sleep)
<input name="Sleep" type="radio" value="5" class="radioCheckBtn">My sleeping is a severe problem (5 to 7 hours lost sleep)
</div>
<h3>10: Recreational Activities</h3>
<div class="options">
<input name="Recreation" type="radio" value="0" class="radioCheckBtn">I can perform all recreation activity without neck pain
<input name="Recreation" type="radio" value="1" class="radioCheckBtn">I can perform recreation activity with only some neck pain
<input name="Recreation" type="radio" value="2" class="radioCheckBtn">I can perform most, not all recreation activity due to neck pain
<input name="Recreation" type="radio" value="3" class="radioCheckBtn">I can only perform some recreation activity due to neck pain
<input name="Recreation" type="radio" value="4" class="radioCheckBtn">I can hardly perform recreational activity due to pain in my neck
<input name="Recreation" type="radio" value="5" class="radioCheckBtn">I cannot perform any recreation activity
</div>
我希望我说得通。
谢谢
【问题讨论】:
-
您能分享一个用于您的单选按钮组的 HTML 设置示例吗?
-
@mwilson 当然,我编辑了上面的代码,谢谢
-
使事物通用/可重用将使您远离重复类型 1 的重复代码
标签: javascript jquery forms if-statement for-loop