jquery - 使用 JQuery 组合单选按钮状态检查
问题描述
我有四个单选按钮。在不同的情况下,所有这些按钮都可以变为可见或隐藏(所有可能的组合)。我需要使用 JQuery 检查这个条件“如果没有隐藏并且没有检查任何一个(以及所有可能的组合)做某事”。
<input type="radio" name="currentOa" id="currentOa1" value="currentOa1">
<input type="radio" name="currentOa" id="currentOa2" value="currentOa2">
<input type="radio" name="currentOa" id="currentOa3" value="currentOa3">
<input type="radio" name="currentOa" id="currentOa4" value="currentOa4">
两个此类可能条件的示例并在 JQuery 中检查如下
if ($("#currentOa1").is(":visible") && $("#currentOa2").is(":hidden") && $("#currentOa3").is(":hidden") && $("#currentOa4").is(":hidden") && $('#currentOa1').prop("checked", false)) {
alert("Current OA1 is not checked");
} else if ($("#currentOa1").is(":visible") && $("#currentOa2").is(":visible") && $("#currentOa3").is(":hidden") && $("#currentOa4").is(":hidden") && $('#currentOa1').prop("checked", false) || $('#currentOa2').prop("checked", false)) {
alert("Please select one of the radiobuttons");
}
如果需要像上面那样硬编码,它有很多 if else 和许多组合。有什么简单的方法吗?
解决方案
为单选按钮使用一些类,并使用该类名检查选择、可见性。
示例代码如下:
var testSelection = function() {
if ($(".rbs:visible").length > 0) {
if ($(".rbs:checked").length > 0) {
var selectn = $(".rbs:checked").attr("value");
alert(selectn + " is selected");
} else {
alert("Please select one of the radiobuttons");
}
} else {
alert("All options are hidden");
}
}
<html>
<head>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
</head>
<body>
<input type="radio" name="currentOa" class="rbs" id="currentOa1" value="currentOa1">
<input type="radio" name="currentOa" class="rbs" id="currentOa2" value="currentOa2">
<input type="radio" name="currentOa" class="rbs" id="currentOa3" value="currentOa3">
<input type="radio" name="currentOa" class="rbs" id="currentOa4" value="currentOa4">
<input type="button" onclick="testSelection()" value="Check">
</body>
</html>
希望它会解决。
推荐阅读
- sql - 如何根据事件类型数据填充行
- java - 如何随着时间的推移隐藏/显示 JPanel(JAVA、图形、动画)
- swift - 快速多行字符串的缩进
- android - 连接到相机 0 时出现 Android 相机错误
- sql-server - 使用公共 IP 的多台服务器的 SQL 复制?
- locust - 用 URL 以外的东西命名任务
- python - 超参数调整 (Hyperas) 和流水线预处理的交叉验证
- angular - Rxjs catchError 导致 TypeScript 类型错误
- reactjs - 如何在不重新渲染嵌套组件的情况下有条件地渲染组件?
- google-apps-script - 在哪里存储 Google App 脚本的静态图像(例如,应用程序徽标)?