jquery - 使用 JQuery 组合单选按钮状态检查

标签 jquery html

我有四个单选按钮。在不同的情况下,所有这些按钮都可以可见或隐藏(所有可能的组合)。我需要使用 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>

希望能解决。

关于jquery - 使用 JQuery 组合单选按钮状态检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59297638/

相关文章:

php - HTTP ://localhost/appears before path

html - 如何为输入边框设置动画并使其从中心扩展?

html - 页面两侧垂直对齐的 div

jquery - KnockoutJS 使用映射插件订阅属性更改

javascript - 使用 jquery 选择表行,但在单击按钮时也选择行,如何防止这种情况发生?

javascript - 使用 Jquery 加载方法和 Slick 插件

javascript - 使用 jQuery 调整表列大小

PHP 将 Class 和 id 写成单引号而不是双引号。为什么?

javascript - 这个jquery如何在meteor助手中实现?

javascript - 无法手动设置 slider