简体   繁体   English

jQuery hide / show div,带有单选按钮控件

[英]jQuery hide/show div, with radio button control

I have few radio buttons with same name. 我有几个同名的单选按钮。

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

and have part of jQuery code, which must show or hide part of code. 并拥有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();
    }
});

Alerts was added for debugging. 添加了警报以进行调试。 It's always alert about 0. No matter which radio is checked now. 它始终是关于0的警报。无论现在检查哪个无线电。 I am hope, you can help me. 我希望,你可以帮助我。 Thank you 谢谢

You can do this: 你可以这样做:

$('[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();
    }
});

Actually, you are doing this: 实际上,你这样做:

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

which will always fetch you the value of the first radio button, whether it's checked or not. 它总是会获取第一个单选按钮的值,无论是否已选中。

In order, to get the value of the checked radio button on change event you can use the :checked selector as above. 为了获得change事件上已检查单选按钮的值,您可以使用:checked选择器,如上所示。

var $oTypes = $('input[name="owner_type"]').change(function () {
    //$('#agents').toggle($oTypes.filter(':checked').val() == 1);
    $('#agents').toggle(this.value == 1);
});
  1. Use the element selector before attribute selector 在属性选择器之前使用元素选择器
  2. Use toggle to set the display state 使用切换来设置显示状态

try something like this 尝试这样的事情

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

Try this, use a :checked selector 试试这个,使用a :checked选择器

DEMO DEMO

$('[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();
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM