2011-10-06 35 views
2

我有一個這樣的形式:jQuery的複選框的選擇和變化類

<form action='' onsubmit='void(0)' class="mainform"> 
       <label class="form3"><input type="checkbox"> One a fancy cross-browser styled checkbox</label> 
       <label class="form3"><input type="checkbox"> two a fancy cross-browser styled checkbox</label> 
       <label class="form3"><input type="checkbox"> Three a fancy cross-browser styled checkbox</label> 
       <label class="form3"><input type="checkbox"> Four a fancy cross-browser styled checkbox</label> 
       <label class="form3"><input type="checkbox"> Five a fancy cross-browser styled checkbox</label> 
       <label class="form3"><input type="checkbox"> Six a fancy cross-browser styled checkbox</label> 
       <label class="form3"><input type="checkbox"> Seven a fancy cross-browser styled checkbox</label> 
       <label class="form3"><input type="checkbox"> eight a fancy cross-browser styled checkbox</label> 
       <label class="form3"><input type="checkbox"> 9 a fancy cross-browser styled checkbox</label> 
       <label class="form3"><input type="checkbox"> 10 a fancy cross-browser styled checkbox</label> 
       <label class="form3"><input type="checkbox"> 11 a fancy cross-browser styled checkbox</label> 
       <label class="form3"><input type="checkbox"> 12 a fancy cross-browser styled checkbox</label> 
       <label class="form3"><input type="checkbox"> 13 a fancy cross-browser styled checkbox</label> 
       <label class="form3"><input type="checkbox"> 14 a fancy cross-browser styled checkbox</label> 
</form> 

現在,我想這樣做。 當用戶選中或取消選中某個複選框時,我想向標籤中添加/刪除類,以便在選中複選框時以及不選中時顯示不同的彩色文本。

我試圖做到這一點liek這樣的:(」。form3' )。

$(document).ready(function(){ 
$('.form3').each(function(i,e) { 
    if(checklist[i] == "") 
    { 
     $(this).find('input[type=checkbox]').attr('checked', false); 
     $(this).appendTo($('form')); 
     $(this).find('input[type=checkbox]').change(function() { 
      $(this).closest('label').addClass("checkselected"); 
     }); 
     $(this).closest('label').removeClass("checkselected"); 

    } 
    else 
    { 
     $(this).find('input[type=checkbox]').attr('checked', true); 
     $(this).find('input[type=checkbox]').change(function() { 
      $(this).closest('label').removeClass("checkselected"); 
     }); 
     $(this).closest('label').addClass("checkselected"); 
    } 
}); 
}); 

現在我知道,這maynot是這樣做,因爲我在裏面的「$這樣做的正確的方式各(函數(I,E)」

這使得它的工作,但只有一次。 我怎樣才能使其與mulltiple點擊相同的複選框,甚至工作。

回答

4

如果我理解正確你的問題,然後你要做的是將一個點擊事件處理程序綁定到所有的複選框,並且向已被點擊的父類label添加/刪除類。如果這是正確的,那麼你可以這樣做:

$("input[type='checkbox']").change(function() { 
    $(this).closest("label").toggleClass("someClass"); 
}); 

toggleClass方法消除了需要檢查的複選框是否被選中。你可以通過在第二個參數顯示類是否應該被添加或刪除,因此,如果你的一些複選框開始已經檢查,你可能要使用:

$("input[type='checkbox']").change(function() { 
    $(this).closest("label").toggleClass("someClass", this.checked); 
}); 

這裏的一個working example以上代碼。

+0

謝謝,這有助於解決添加和刪除類的問題。我會發布另一個問題,當我檢查並取消選中這些框時,如果更改「清單」的數組值,會發生什麼情況。 – ssdesign