2016-04-21 37 views
0

(我已經瞭解一些這方面的其他問題,但沒有使用此方法)

我有一些隱藏的字段檢查時,他們各自的複選框顯示,我也想,當我取消選中時,選中該複選框並相反的,使這些領域需要

何時檢查:。

  • 顯示輸入並使其成爲必需

當取消選中:

  • 清潔的輸入值,除去必需的屬性,並再次將其隱藏。

這就是我想,但它不工作(所需部分):

$(':checkbox').change(function(event) { 
    $(this).parent('.item').find('.input').toggleClass('hide', (!$(this).is(':checked'))); 
    $(this).parent('.item').find('.input :checkbox').prop('checked', false, (!$(this).is(':checked'))); 
    $(this).parent('.item').find('.input input').not(':checkbox, .opt').prop('required', true, ($(this).is(':checked'))); 
    $(this).parent('.item').find('.input input').not(':checkbox').val('').not('.opt').prop('required', false, (!$(this).is(':checked'))); 
    if (this.id == 'price2') { 
    $('.sub-rent .input').toggleClass('hide'); 
    $('.rent :checkbox').prop('checked', false, (!$(this).is(':checked'))); 
    $('.rent').toggleClass('hide', (!$(this).is(':checked'))); 
    } 
}); 

HTML結構共分三組:

  • 含有隱藏一個複選框輸入
  • 帶有兩個隱藏輸入的複選框
  • 複選框帶有兩個複選框,每個隱藏輸入兩個(第一個也是與複選框)。

我也在尋找機會,知道如何儘可能優化代碼。

https://jsfiddle.net/j30v4z9k/

+1

,我不知道.prop()'這三個參數的'任何實現的。 –

+0

http://api.jquery.com/prop/#prop-propertyName-function在這種情況下,它就像一個條件。 –

+0

是的,它仍然需要兩個參數:屬性名稱和返回值的函數。 –

回答

0

正如@PaulAbbott說,prop()不採取三個參數,所以:

$(':checkbox').change(function(event) { 
    $(this).parent('.item').find('.input').toggleClass('hide', (!$(this).is(':checked'))); 
    $(this).parent('.item').find('.input :checkbox').prop('checked', false); 
    $(this).parent('.item').find('.input input').not(':checkbox').val('').not(':checkbox, .opt').prop('required', ($(this).is(':checked'))); 
    if (this.id == 'price2') { 
    $('.sub-rent .input').toggleClass('hide'); 
    $('.rent').toggleClass('hide', (!$(this).is(':checked'))); 
    } 
});