2012-06-27 52 views
2

我很新的jQuery的,所以我的道歉,如果有什麼明顯我錯過了,但......我只是希望能有我的窗體的一部分被隱藏,當用戶點擊一個複選框。複選框選中出現,儘管檢查

所以,我寫這個小jQuery腳本:

$("#belonging_entire_world").toggle(function() { 
      $("#access_for_friends, #access_for_groups").fadeOut(); 
     }, function(){ 
      $("#access_for_friends, #access_for_groups").fadeIn(); 
}); 

當我點擊標籤id爲「belonging_entire_world」的複選框,它隱藏我希望表單的部分(由#access_for_friends代表的部分& #access_for_groups),如果我再次點擊,它再次顯示了這個部分,但複選框「belonging_entire_world」我一直保留檢查未選中視覺...

如果我打開Firebug的腳本運行後,我看到我的複選框確實有checked = checked屬性...仍然,它在瀏覽器中看起來沒有選中(在所有的瀏覽器)...

我試圖添加,在切換功能的第一功能如下:

$("#belonging_entire_world").attr('checked', true); 

但仍...仍是一樣的,如果它是未選中...

這是推動我瘋了,我沒有看到,除去jQuery代碼的另一種選擇,我真的不明白這一點......我把下面的視圖的一部分:

<div id="Belonging-Access-Control"> 
     <h2> Who will be able to see & access this? </h2> 
     <div class="field" id="entire_world"> 
     <%= f.check_box(:entire_world) %> 
     <%= f.label(:entire_world, "The entire world!") %> 
     </div> 

     <div class="field" id="access_for_friends"> 
     <%= f.check_box(:access_for_friends) %> 
     <%= f.label(:access_for_friends, "My friends") %> 
     </div> 

和HTML我檢查後的頁面複選框(螢火蟲輸出):

<div id="Belonging-Access-Control"> 
<h2> Who will be able to see &amp; access this? </h2> 
<div id="entire_world" class="field"> 
<input type="hidden" value="0" name="belonging[entire_world]"> 
<input id="belonging_entire_world" type="checkbox" value="1" name="belonging[entire_world]" checked="checked"> 
<label for="belonging_entire_world">The entire world!</label> 
</div> 
<div id="access_for_friends" class="field" style="display: none;"> 
<input type="hidden" value="0" name="belonging[access_for_friends]"> 
<input id="belonging_access_for_friends" type="checkbox" value="1" name="belonging[access_for_friends]"> 
<label for="belonging_access_for_friends">My friends</label> 
</div> 
+0

您正在使用什麼版本的jQuery? –

+0

@Andrew:jQuery的版本:1.7.2 – citraL

+0

您確保ID:belonging_entire_world $( 「#belonging_entire_world」)ATTR( '檢查',真)。請參閱複選框ID? – Cygnusx1

回答

1

這似乎是使用.toggle()的問題。如果您使用此功能,它可以嗎?:

$("#belonging_entire_world").click(function() { 
    if (this.checked) { 
     $("#access_for_friends, #access_for_groups").fadeOut(); 
    } else { 
     $("#access_for_friends, #access_for_groups").fadeIn(); 
    } 
}); 

如果您想要相反的衰落,您可以切換淡入淡出。這可能是一個更好的解決方案,以防複選框開始「檢查」。因此,此代碼將根據複選框的狀態隱藏/顯示其他div,而不是在切換它的哪個階段。

+0

謝謝! ...正如你所說的那樣使用點擊時它會起作用! (我只需要在你的回答中反轉fadeIn,fadeOut)。我非常生氣,非常感謝! – citraL

+0

沒問題!我不確定爲什麼切換在這種情況下很奇怪。但是,是的,不知道你想要哪種方式褪色,所以你去! – Ian

-1

.toggle(),因爲它提到的作品,但另一種方式,我個人更喜歡是檢查的checkbox

這樣的狀態,你可以鏈的不同條件事件顯示/隱藏多餘的部分表格。

+1

很抱歉,但切換,因爲有人提到應該工作,但不工作 – citraL

+0

......我的意思,因爲它是由ianpgall提到 – johncho