我正在构建一个与后端服务通信的rails站点,后端服务返回某个对象集的列表。然后,UI打印表中的对象值列表,并允许用户拒绝或批准行,每行都有一个approval和denial复选框。我想知道是否有一种方法可以一次只选中一个复选框,因为它们应该是相互排斥的。查看代码如下
<td><%= check_box_tag 'approve_request_ids[]', e.request_id %></td>
<td><%= check_box_tag 'decline_request_ids[]', e.request_id %></td>发布于 2014-07-25 11:53:52
您可以像这样使用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);
});发布于 2014-07-25 15:40:56
一种一次只允许选中一个复选框的方法
我最初的想法是使用单选按钮来代替-根据评论,您将希望提供一个“取消选择”按钮,这是使用JS实现的。
让我详细说明您将如何执行此操作,以及如何处理复选框:
--
单选按钮
你可以使用单选按钮--如果你点击一个被选中的单选按钮,JQuery会“取消选择”它:
How to check/uncheck radio button on click?
#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);
}
});--
复选框
使用JS可以“取消选中”该复选框--您需要做的就是使用JS捕获"check“操作,然后”取消选中“该行的相应复选框。这将确保您只能选择一个复选框,同时提供“无”选择:
#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);
}
});https://stackoverflow.com/questions/24946752
复制相似问题