我有一个复选框表,我想验证是否至少检查过其中一个复选框。我写了一个小函数来迭代所有具有特定名称的复选框,并检查checked属性,但是我的代码从未捕获到没有选中复选框的场景。
表格定义
<div id="testTable">
<table class="table table-striped">
<caption></caption>
<thead>
<tr>
<th>Test</th>
<th>Description</th>
</tr>
</thead>
<tr>
<td>
<input type="checkbox" id="testA" name="test" title="Run TestA" />
<label for="testA">TestA</label>
</td>
<td>Description of TestA</td>
</tr>
<tr>
<td>
<input type="checkbox" id="testB" name="test" title="Run TestB" />
<label for="testB">TestB</label>
</td>
<td>Description of TestB</td>
</tr>
</table>
</div>
测试按钮
<div class="row">
<div class="form-group">
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="btnRunTests">Run selected test(s)</button>
</span>
</div>
</div>
脚本
<script type="text/javascript">
$(document).ready(function () {
$('#btnRunTests').click(function ()
{
if (!anyTestsChecked)
{
$('#divAlertMain').html('<div id="divAlert" class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">x</button>You must select at least one test to run.</div>');
}
else
{
$('#divAlertMain').html('<div id="divAlert" class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">x</button>Good job!</div>');
}
window.setTimeout(function () {
$('#divAlert').hide('slow');
}, 10000);
});
});
function anyTestsChecked()
{
var chk = document.getElementsByName('test');
var len = chk.length;
var foundChecked = false;
var i = 0;
while (i < len && !foundChecked)
{
if (chk[i].type === 'checkbox' && chk[i].checked)
{
foundChecked = true;
}
i++;
}
return foundChecked;
}
</script>
答案 0 :(得分:1)
您的函数anyTestsChecked
永远不会运行。你只是检查它是否存在。在if语句中将()
添加到函数调用的末尾。
if (!anyTestsChecked())
答案 1 :(得分:1)
您可以使用以下代码实现相同的功能。 (无需为此编写额外功能)
<script type="text/javascript">
$(document).ready(function () {
$('#btnRunTests').click(function () {
if ($("input[name='test']").prop('checked') == false) {
$('#divAlertMain').html('<div id="divAlert" class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">x</button>You must select at least one test to run.</div>');
}
else {
$('#divAlertMain').html('<div id="divAlert" class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">x</button>Good job!</div>');
}
window.setTimeout(function () {
$('#divAlert').hide('slow');
}, 10000);
});
});
</script>