2009-11-25 90 views
5

我有一个复杂的jQuery表单,如果某个复选框被选中,我想禁用多个表单元素。我使用jQuery 1.3.2和所有相关的插件。我在这里做错了什么?谢谢,达科他州当检查复选框时,jQuery禁用表单元素

这里是我的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> 

这里是我的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'); }); 

回答

4

有几件事情应该改变。首先,实际的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'); 
    } 
}); 
+0

仍然无法正常工作,但看起来应该如此。是否可能bind()比onchange更脆弱,即使不太兼容。我会继续玩。嗯。 – Dakota 2009-11-25 19:35:36

+0

我最终消除了元素容器类,因为它并没有表现,我和同去。 $(“元素切换输入‘)绑定(’点击”,函数(){VAR 输入= $(本).closest('li.form-item')。find('input,select'); if($(this).attr('checked'))inputs.attr('disabled',true); else inputs.removeAttr('disabled'); $(this).removeAttr('disabled'); }); 再次感谢,D – Dakota 2009-11-25 21:07:47

0

<div class='element-container'>不是$('.element-toggle input')父母就是你们的榜样

10

只是一个小闻:因为jquery 1.6你不应该使用$(this).attr('checked')这总是如此,而是$(this).prop('checked')

也建议使用$(this).prop('disabled')(以测试元素是否被禁用)和$(this).prop('disabled', newState)而不是attr

+0

if语句也可以省略,从而使input_prop('disabled',$(this).prop('checked'));''' – 2014-11-25 18:57:03