选中复选框或单选按钮时如何显示隐藏字段?

How to show hidden field when a check box or radio buttons are checked?

我有一个带有一些单选按钮和复选框的表单。一些 checkboxes/radio 旁边有一些隐藏的 div 用户。隐藏的 dividers 应该只有在用户 select 相应的 radio/checkbox.

时才可见

每个 radio/checkbox 都有一个这种格式的值 123:456 相应的隐藏 divider 将有一个 id 属性等于 group_123_456

我能够从每个项目(复选框或单选框)的值中找到我需要 visible/hide 的 divider id 的值。

我想我可以利用 change() 事件找到一个方法。我以为我可以评估每个项目。如果项目被检查,显示相应的 div 否则隐藏它。

这是我所做的

$("input[type='radio'], input[type='checkbox']").change(function(e) {
    $(this).each(function(index, item){
        var newGroupName = '';
        if( $(item).is(':checked') ){
            console.log( $(item).val() + ' is checked' );
            newGroupName = getGroupElement( $(this).val() );
            $('#' + newGroupName).show();
        } else {
            console.log( $(item).val() + ' is NOT checked' );
            newGroupName = getGroupElement( $(this).val() );
            $('#' + newGroupName).hide();
        }
    });
}).change();

以上代码适用于复选框,但不适用于单选按钮。

我创建了一个 fiddle 来让您更好地了解我在这里要做什么 https://jsfiddle.net/oke8qLwg/2/

如何在每次使用更改输入值时show/hide正确divider?

https://jsfiddle.net/oke8qLwg/

这是我为解决这个问题所做的工作

$(":radio").change(function(e) {

        var name = $(this).attr('name');

        $('input[name='+name+']').each(function(index, item){
            applyLogic(item);
        });
});

$(":checkbox").change(function(e) {
        applyLogic( $(this) );
});


function applyLogic(item)
{

    var newGroupName = getGroupElement( $(item).val() );

    if( $(item).is(':checked') ){

        $('#' + newGroupName).show();

    } else {

        $('#' + newGroupName).hide();
    }

}

每次更改单选按钮时,我都会遍历具有相同输入名称的按钮,然后应用 show/hide 逻辑。