javascript - jQuery 隐藏/显示 div,带有单选按钮控件

标签 javascript jquery html

我有几个同名的单选按钮。

Office <input type="radio" name="owner_type" value="0" />
Agent <input type="radio" name="owner_type" value="1" />

并且有部分 jQuery 代码,必须显示或隐藏部分代码。

$('[name="owner_type"]').change(function(){
    if ($('[name="owner_type"]').val() == 1) {
        alert("it's 1 now");
        $('#agents').show();
    } else {
        alert("it's 0 now");
        $('#agents').hide();
    }
});

添加了警报以进行调试。它总是关于 0 的警报。无论现在检查哪个 radio 。我希望,你能帮助我。谢谢

最佳答案

你可以这样做:

$('[name="owner_type"]').change(function () {
    if ($('[name="owner_type"]:checked').val() === "1") {
        alert("it's 1 now");
        $('#agents').show();
    } else {
        alert("it's 0 now");
        $('#agents').hide();
    }
});

实际上,你正在这样做:

$('[name="owner_type"]').val()

它总是会获取第一个单选按钮的值,无论它是否被选中。

为了获取 change 事件中选中单选按钮的值,您可以使用 :checked选择器如上。

关于javascript - jQuery 隐藏/显示 div,带有单选按钮控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20094634/

相关文章:

javascript - 重建时未设置配置选项 - Bootstrap Multiselect

javascript - 使用 jQuery 解析 JSON

javascript - 如何使用 PHP 获取 JSON 输出

javascript - 将变量从 HTML 传递到 JS 文件

javascript - 在字符串末尾添加 X 行,从开头删除相同数量的行

javascript - 使用 javascript 打印隐藏在屏幕上的部分

html - 子元素在 flex 容器中不可见

html - 仅在 Firefox 中过渡期间轮廓变为白色

javascript - 当元素进入视口(viewport)时,在离开视口(viewport)之前水平滚动其全部内容

javascript - Firebase (V9) 中的登录持久性