如何在未选中项目时禁用该按钮

How to disable the button when item are not checked?

本文关键字:按钮 项目      更新时间:2023-09-26

我有多个与按钮单击事件相关联的复选框项。但我试图禁用按钮时,没有复选框项被选中。下面是我的代码:

    <script>
    $( document ).ready(function() {
        $('#cbOne').click(function(){
            if($(this).attr('checked') == false){
                $('#target-group').attr("disabled","disabled");
            }
            else {
                $('#target-group').click(function() {
                    var targetGroups = $("input:checkbox:checked", ".actors-$i").map(function() {
                        return $(this).val();
                    }).get();
                    $('#out').append(targetGroups.join(','));
                });
            }
        });

    });
</script>
<button class="aui-button" id="target-group" style="float: right">Generate Target Group</button>

代码工作正常,但按钮是启用的,即使没有复选框被选中

尝试:

$('#target-group').attr("disabled", true);

如果不成功尝试:

$('#target-group').prop("disabled", true);

试一下:

$(document).ready(function() {
    $('#target-group').click(function() {
        if ($('input:checkbox:checked').length == 0) {
            return;
        }
        var targetGroups = $("input:checkbox:checked", ".actors-$i").map(function() {
            return $(this).val();
        }).get();
        $('#out').append(targetGroups.join(','));
    });
});
演示

试试这个:

$(document).ready(function () {
    //To check whether the checkbox is checked or not
    $('input[type="checkbox"]').click(function () 
    {
        if ($(this).prop("checked") == true) {
            $("#target-group").show();
        }
        else if ($(this).prop("checked") == false) {
            $("#target-group").hide();
        }
    }
});