使用jQuery启用/禁用复选框
问题描述:
我想仅在复选框被选中时启用一组复选框。否则,我希望他们保持残疾。使用jQuery启用/禁用复选框
这里是我的代码:
的jQuery:
$(document).ready(function() {
$(function() {
enable_cb();
$("#university").click(enable_cb);
});
function enable_cb() {
if (this.checked) {
$('input.uni').prop('disabled', false);
} else {
$('input.uni').prop('disabled', true);
}
}
});
HTML:
<form action="test.php" method="post" enctype="multipart/form-data" id="test-form" novalidate>
<input name="table[]" type="checkbox" value="university" id="university"/>
University<br>
<input type="checkbox" disabled="true" class="uni" value="1" />
A<br>
<input type="checkbox" disabled="true" class="uni" value="2" />
B<br>
<input type="checkbox" disabled="true" class="uni" value="3" />
C<br>
<input type="checkbox" disabled="true" class="uni" value="3" />
D<br>
<input name="table[]" type="checkbox" value="buildings" />
Buildings<br>
<input name="table[]" type="checkbox" value="offices" />
Offices<br>
<input name="table[]" type="checkbox" value="halls" />
Halls<br>
<input name="table[]" type="checkbox" value="labs" />
Labs<br>
<input name="table[]" type="checkbox" value="studios" />
Studios<br>
<input name="table[]" type="checkbox" value="machines" />
Machines<br>
<input name="table[]" type="checkbox" value="facilities" />
Facilities<br>
</form>
为什么这不是为我工作吗?
答
改为使用.on()
方法并使用'click'触发器。检查下面的代码片段
function enable_cb() {
if (this.checked) {
$('input.uni').prop('disabled', false);
} else {
$('input.uni').prop('disabled', true);
}
}
$(function() {
enable_cb();
$("#university").on('click',enable_cb);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="test.php" method="post" enctype="multipart/form-data" id="test-form" novalidate>
<input name="table[]" type="checkbox" value="university" id="university"/>
University<br>
<input type="checkbox" disabled="true" class="uni" value="1" />
A<br>
<input type="checkbox" disabled="true" class="uni" value="2" />
B<br>
<input type="checkbox" disabled="true" class="uni" value="3" />
C<br>
<input type="checkbox" disabled="true" class="uni" value="3" />
D<br>
<input name="table[]" type="checkbox" value="buildings" />
Buildings<br>
<input name="table[]" type="checkbox" value="offices" />
Offices<br>
<input name="table[]" type="checkbox" value="halls" />
Halls<br>
<input name="table[]" type="checkbox" value="labs" />
Labs<br>
<input name="table[]" type="checkbox" value="studios" />
Studios<br>
<input name="table[]" type="checkbox" value="machines" />
Machines<br>
<input name="table[]" type="checkbox" value="facilities" />
Facilities<br>
</form>
+0
Owwwh终于明白了,非常感谢你^^ – Learner
究竟是什么错误你好吗? –
它在这里工作https://jsfiddle.net/yhynuv4L/。你能解释它是如何不起作用的吗? – AmmarCSE
您首次调用'enable_cb();'没有'this'上下文,添加一个[apply](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/ Global_Objects/Function/apply) –