gpt4 book ai didi

JavaScript 函数确定是否选中任何复选框

转载 作者:行者123 更新时间:2023-12-02 17:15:40 24 4
gpt4 key购买 nike

我有一张复选框表,我想验证是否至少选中了其中一​​个。我编写了一个小函数来迭代具有特定名称的所有复选框并检查选中的属性,但我的代码从未捕获未选中复选框的情况。

表定义

<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>

最佳答案

您可以使用下面的代码实现同样的效果。 (无需为此编写额外的函数)

<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>

关于JavaScript 函数确定是否选中任何复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24458139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com