每行有相互独立的复选框

时间:2014-07-25 01:42:36

标签: html ruby-on-rails ruby

我正在构建一个与后端服务进行通信的rails站点,后端服务返回一组对象的列表。然后,UI打印出表中的对象列表值,并允许用户拒绝或批准每行的批准和拒绝复选框。我想知道是否有办法只允许一次检查一个复选框,因为它们应该是互斥的。查看代码如下

<td><%= check_box_tag 'approve_request_ids[]', e.request_id %></td>
<td><%= check_box_tag 'decline_request_ids[]', e.request_id %></td>

2 个答案:

答案 0 :(得分:1)

你可以使用这样的jquery来做到这一点:

<table>
  <tr>  
    <td><%= check_box_tag 'approve_request_ids[]', e.request_id %></td>
    <td><%= check_box_tag 'decline_request_ids[]', e.request_id %></td>
  </tr>
</table>

你的Jquery:

$('tr .checkbox').click(function () {
  var state = $(this).prop("checked");
  $(this)
      .parent()
      .parent()
      .find('input.checkbox:checked')
      .prop("checked", false);

  $(this).prop("checked", state);
});

答案 1 :(得分:1)

  

一种只允许一次检查一个复选框的方法

我最初的想法是使用单选按钮 - 根据评论,你需要做一个让“取消选择”按钮的规定,这是你用JS实现的。

让我详细说明你是如何做到这一点的,以及你如何处理复选框:

-

广播按钮

可以使用单选按钮 - 你必须这样做才能点击一个被“选中”的按钮,JQuery会“取消选择”它:

How to check/uncheck radio button on click?

JSFiddle

#app/views/controller/your_view.html.erb
<table>
    <tr>
        <td><input type="radio" name="sex" value="male">Male</td>
        <td><input type="radio" name="sex" value="female">Female</td>
    </tr>
</table>

#app/assets/javascripts/application.js
$("tr").on("mousedown", ":radio", function(){
  var $self = $(this);
  if( $self.is(':checked') ){
    var uncheck = function(){
      setTimeout(function(){$self.removeAttr('checked');},0);
    };
    var unbind = function(){
      $self.unbind('mouseup',up);
    };
    var up = function(){
      uncheck();
      unbind();
    };
    $self.bind('mouseup',up);
    $self.one('mouseout', unbind);
  }
});

-

<强>复选框

JSFiddle

可以使用JS“取消选中”复选框 - 您需要做的是使用JS捕获“检查”操作,然后“取消选中”该行的相应复选框。这将确保您只能选择一个复选框,同时配置“无”选择:

#Table same setup as Tiago Farias


#app/assets/javascripts/application.js
$("tr").on("change", ":checkbox", function(){
   if( $(this).is(":checked") ) {
       $(this).parent().parent().find(":checkbox").not($(this)).attr('checked', false);
   }
});
相关问题