按钮未启用,如果复选框处于打开状态

button is not being enabled if checkbox is on

本文关键字:于打开 状态 复选框 如果 启用 按钮      更新时间:2023-09-26

我想仅在复选框打开时才启用按钮。我在这里做错了什么?提前谢谢..

索引.html

<p><input id="agree" type="checkbox" /> I agree</p>
<input id="continue" value="continue" type="button" disabled="disabled" />

自定义.js

$( document ).ready(function () {
    $('#agree').change(function () {
        var state = $(this).attr('value');
        if (state == 'on') {
            $('#continue').removeAttr('disabled')
        } else if (state == '') {
            $('#continue').attr('disabled','disabled');
        }
    });
});

您可以将其简化为以下内容:

这里的例子

$('#agree').on('change', function () {
    $('#continue').attr('disabled', !this.checked);
});

$('#agree').on('change', function () {
    $('#continue').attr('disabled', !this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><input id="agree" type="checkbox" />I agree</p>
<input id="continue" value="continue" type="button" disabled="disabled" />

您的代码不起作用的原因是您使用了.attr()。由于没有value属性,因此需要使用.prop() 。但这仍然不起作用,因为该值将始终返回on .您需要获取访问this.checked.prop('checked')checked 属性 - 使用原始代码段的工作示例。

$('#agree').on('change', function () {
    if (this.checked) {
        $('#continue').removeAttr('disabled')
    } else {
        $('#continue').attr('disabled', 'disabled');
    }
});

试试这个:

$( document ).ready(function() {
  $('#agree').change(function() {
        if(this.checked) {
            $('#continue').removeAttr('disabled')
        } else {
            $('#continue').attr('disabled','disabled');
        }
    });
});    

如果要检查输入是否已选中:

 state = $(this).prop( "checked" );

这将返回布尔值(如果选中,则为 true,如果未选中则为 false)。