2012-09-26 149 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