Dak*_*ota 5 forms checkbox jquery javascript-events
我有一个复杂的jQuery表单,如果选中某个复选框,我想禁用几个表单元素.我正在使用jQuery 1.3.2,以及所有相关的插件.我在这做错了什么?谢谢,达科他州
这是我的HTML:
<li id="form-item-15" class="form-item">
<div class='element-container'>
<select id="house_year_built" name="house_year_built" class="form-select" >
...Bunch of options...
</select>
<input type="text" title="Original Purchase Price" id="house_purchase_price" name="house_purchase_price" class="form-text money" />
<input type="text" title="Current Home Debt" id="house_current_debt" name="house_current_debt" class="form-text money" />
</div>
<span class="element-toggle">
<input type="checkbox" id="house_toggle" />
<span>Do not own house</span>
</span>
</li>
Run Code Online (Sandbox Code Playgroud)
这是我的jQuery:
$('.element-toggle input').change(function () {
if ($(this).is(':checked')) $(this).parents('div.element-container').children('input,select').attr('disabled', true);
else $(this).parents('div.element-container').children('input,select').removeAttr('disabled'); });
Run Code Online (Sandbox Code Playgroud)
小智 10
只是一个小问题:因为jquery 1.6你不应该使用$(this).attr('checked')哪个总是如此,而是$(this).prop('checked').
建议使用$(this).prop('disabled')(测试元素是否被禁用),$(this).prop('disabled', newState)而不是attr.
有一些事情应该改变。首先,实际的 HTML 结构与您在 JavaScript 中查询的内容(特别是调用parents())不匹配。其次,绑定到click事件将为 IE 提供更好的支持,因为 IE 有时会等到change元素失去焦点后才触发事件。
$('.element-toggle input').bind('click', function () {
var inputs = $(this).closest('li.form-item').find('div.element-container').children('input,select');
if ($(this).attr('checked')) {
inputs.attr('disabled', true);
} else {
inputs.removeAttr('disabled');
}
});
Run Code Online (Sandbox Code Playgroud)