首页 > 解决方案 > 使用 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 和许多组合。有什么简单的方法吗?

标签: jqueryhtml

解决方案


为单选按钮使用一些类,并使用该类名检查选择、可见性。

示例代码如下:

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>

希望它会解决。


推荐阅读