[英]Allow only one radio button to be selected from multiple groups of checkboxes
我有许多帐户项目。
我在列表中显示这些内容,例如
<md-list-item ng-repeat="item in items">
对于每个这样的项目,我会在一个组中显示三个单选按钮,其值如下
现在,用户可以为每组单选按钮选择一个值,但是我要执行的操作只有一个管理员。
因此,如果选择了admin值,则我应阻止所有其他admin单选按钮。
如何才能做到这一点?
有一个ng-change方法,将admin项目存储在scope属性中,以跟踪选择了admin的项目:
$scope.radioChanged = function (item) {
if (item.selectedValue == "admin") {
$scope.admin = item;
}
else if (item == $scope.admin) {
$scope.admin = undefined;
}
};
然后在admin单选按钮上使用ng-disabled,如果已选择管理员并且admin不是当前项目,它将禁用单选按钮。
<div ng-repeat="item in items">
<label><input type="radio" name="{{item.id}}" value="admin" ng-model="item.selectedValue" ng-change="radioChanged(item)" ng-disabled="admin && item != admin"/>admin</label>
<label><input type="radio" name="{{item.id}}" value="user" ng-model="item.selectedValue" ng-change="radioChanged(item)"/>user</label>
<label><input type="radio" name="{{item.id}}" value="moderator" ng-model="item.selectedValue" ng-change="radioChanged(item)"/>moderator</label>
</div>
我会创建一个变量,也许是adminExists
,当您在任意单选按钮上选择“ Admin”时,该变量将设置为true
。 然后, if(adminExists && !isSelected)
,则所有“ Admin”单选按钮都将被禁用,如果该单选按钮是所选的admin按钮,则isSelected
为true。
下面的代码将选中的单选按钮的值与其他单选按钮的值进行比较,以查看它们是否匹配(在这种情况下,如果值是“ admin”)。 然后,它将取消选择具有该值的所有单选输入元素,然后检查最初单击或选择的元素以将其设置为活动状态。 您也可以根据需要将函数更改为使用数据属性而不是值。
$(".group input[type=radio]").bind("click change keydown focus", function () { var el = $(this); var val = el.val(); if (el.prop("checked", true) && val == "admin") { $(".group input[type=radio]").each(function () { if ($(this).val() == "admin") $(this).prop("checked", false); }); el.prop("checked", true); } });
.choice { display:block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form> <div class="group"> <div class="choice"> <input type="radio" name="group[0][]" value="admin" /> <label>Admin</label> </div> <div class="choice"> <input type="radio" name="group[0][]" value="user" /> <label>User</label> </div> <div class="choice"> <input type="radio" name="group[0][]" value="moderator" /> <label>Moderator</label> </div> </div> <div class="group"> <div class="choice"> <input type="radio" name="group[1][]" value="admin" /> <label>Admin</label> </div> <div class="choice"> <input type="radio" name="group[1][]" value="user" /> <label>User</label> </div> <div class="choice"> <input type="radio" name="group[1][]" value="moderator" /> <label>Moderator</label> </div> </div> </form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.