如果启用了复选框,则不会启用按钮

时间:2015-03-13 02:33:08

标签: javascript jquery

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

的index.html

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

custom.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');
        }
    });
});

3 个答案:

答案 0 :(得分:2)

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

Example Here

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

&#13;
&#13;
$('#agree').on('change', function () {
    $('#continue').attr('disabled', !this.checked);
});
&#13;
<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" />
&#13;
&#13;
&#13;

您的代码无法运行的原因是因为您使用的是.attr()。由于没有value属性,因此您需要使用.prop()。这仍然无法工作,因为该值将始终返回on。您需要获取访问checkedthis.checked - working example using your original snippet.prop('checked')媒体资源。

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

答案 1 :(得分:1)

试试这个:

$( document ).ready(function() {

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

});    

答案 2 :(得分:0)

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

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

返回布尔值(如果选中则返回true;如果未选中则返回false)。