我想仅在启用复选框时启用按钮。我在这做错了什么?提前谢谢..
的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');
}
});
});
答案 0 :(得分:2)
您可以将其简化为以下内容:
$('#agree').on('change', function () {
$('#continue').attr('disabled', !this.checked);
});
$('#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;
您的代码无法运行的原因是因为您使用的是.attr()
。由于没有value
属性,因此您需要使用.prop()
。这仍然无法工作,因为该值将始终返回on
。您需要获取访问checked
或this.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)。