2009-11-25 57 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

相關問題