2012-09-26 56 views
0

我有一個活動複選框和一個高亮複選框。Jquery選中複選框1時,選中複選框2

enter image description here

我想活動複選框自動檢查亮點複選框被選中時激活。我對於探索prop()還是做了添加屬性的醜陋綁定感到茫然。

我最終尋找最乾燥的推薦,當然任何代碼片段都歡迎!

有點惱人,因爲每個複選框(雖然旁邊的海誓山盟在表都是自己的形式,這是與阿賈克斯的改變提交。

<td> 
    <% form_for(:catalog_item, catalog_item.item, :url => set_admin_catalog_item_path(catalog_item), :html => {:class => 'ajax'}) do |f| %> 
    <%= f.check_box :active %> 
    <% end %> 
</td> 
<td> 
    <% form_for(:catalog_item, catalog_item, :url => set_admin_catalog_item_path(catalog_item), :html => {:class => 'ajax'}) do |f| %> 
    <%= f.check_box :highlight %> 
    <% end %> 
</td> 
+0

你能顯示你的代碼嗎? HTML? –

+0

現在拉那個分支,抱歉完全忘了把代碼放進去。BRAIN FART!儘管我嘗試了道具,但無法讓它滾動。 – jahrichie

回答

3

入住這FIDDLE

$(function() { 
    $('.active').on('click', function(){ 
     $(this).next().attr('checked' , $(this).is(':checked')); 
    }); 

});​ 

也可以使用

$(this).next().prop('checked' , $(this).is(':checked')); 
+0

謝謝!上面添加了我的代碼。無法讓這工作不幸 – jahrichie

1

jsFiddle

由於HTML這樣的:

HTML

<div id="ActHigh"> 
    <table> 
     <thead> 
      <tr> 
       <th> 
        <p> 
         Active 
        </p> 
       </th> 
       <th> 
        <p> 
         Highlight 
        </p> 
       </th> 
      </tr> 
     </thead> 
     <tbody> 
      <tr> 
       <td> 
        <input type="checkbox" name="act01" class="chk-active" /> 
       </td> 
       <td> 
        <input type="checkbox" name="hig01" class="chk-highlight" /> 
       </td> 
      </tr> 
      <tr> 
       <td> 
        <input type="checkbox" name="act02" class="chk-active" /> 
       </td> 
       <td> 
        <input type="checkbox" name="hig02" class="chk-highlight" /> 
       </td> 
      </tr> 
      <tr> 
       <td> 
        <input type="checkbox" name="act03" class="chk-active" /> 
       </td> 
       <td> 
        <input type="checkbox" name="hig03" class="chk-highlight" /> 
       </td> 
      </tr> 
     </tbody> 
    </table> 
</div> 

您可以使用jQuery這樣的:

SCRIPT

<script type="text/javascript"> 
    $(function() { 
     // This will file through all "active" type checkboxes 
     $("#ActHigh .chk-active").each(function(i){ // Keep in mind, this refernce relys on active and highlight chkboxes being one right after the other in html 
      $(this).change(function(e) {// this tells us to do something on the current checkbox when it is checked, via mouse or keyboard 
       // this looks for the "highlight" checkbox with the same INDEX as the currently changed "active" checkbox 
       $("#ActHigh .chk-highlight").filter(function(ii){ return ii == i; }).prop("checked", $(this).prop("checked")); 
      }); 
     }); 
    }) 
</script> 
+0

這幾乎適合我!它適用於頁面上的第一個複選框,但在此之後它不會。任何方式讓我適應?提前致謝!!! – jahrichie

+0

這一切都在你的「選擇器」中。看到這個[jQuery API片斷](http://api.jquery.com/category/selectors/)以獲取更精確的信息。長話短說,如果你想讓它抓住文件上的所有內容,只需使用與它們相關的類。但是,我使用了包裝元素標籤的ID來提高我的示例中的精度。如果出現問題,這樣可以更容易地進行調試,因爲這些都是基於輸入的INDEX。這意味着您必須保持它們在HTML中出現的順序。 – SpYk3HH