sma*_*hat 2 html javascript checkbox jquery button
button如果未checkbox选中,我想禁用我的。checkbox应该检查至少一项以启用该按钮。
我的HTML:
<table border="1">
<tr>
<th></th>
<th>Name</th>
</tr>
@foreach($clients as $client)
<tr>
<td><input type="checkbox" name="status[]" value="$client['id']" class="checkbox"></td>
<td>{{ $client['name'] }}</td>
</tr>
@endforeach
</table>
<button type="button" id="off" class="btn btn-default" data-toggle="modal" data-target="#offer" disabled>Choose New Offer</button>
Run Code Online (Sandbox Code Playgroud)
我尝试了以下jQuery代码:
<script>
$(function() {
$('.checkbox').click(function() {
if ($(this).is(':checked')) {
$('#off').removeAttr('disabled');
} else {
$('#off').attr('disabled', 'disabled');
}
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
该按钮是disabled默认设置。如果选中一个复选框,则启用它;如果未选中,则再次禁用。但是问题是当我选中多个复选框并取消选中一个复选框时,它仍然被禁用,尽管仍然选中了许多复选框。
您应该检查是否选中了任何复选框,而不是检查是否选中了单击的复选框。您可以通过选中所有选中的复选框,$('.checkbox:checked')然后检查返回的jQuery对象的长度来实现。
$(function() {
$('.checkbox').click(function() {
if ($('.checkbox:checked').length > 0) {
$('#off').removeAttr('disabled');
} else {
$('#off').attr('disabled', 'disabled');
}
});
});
Run Code Online (Sandbox Code Playgroud)
您需要查看是否选中任何复选框来对禁用状态做出决定。
您还应该使用propand notattr来确保跨浏览器兼容性。
$(function () {
$('.checkbox').click(function () {
$('#off').prop('disabled', !$('.checkbox:checked').length);
});
});
Run Code Online (Sandbox Code Playgroud)
JSFiddle: http://jsfiddle.net/TrueBlueAussie/L72Lv6h1/
propfordisabled可以采用布尔标志值,因此不需要if else.