javascript - 根据数据属性启用或禁用复选框

标签 javascript jquery html

我有一组具有 data-groupiddata-multichoice 属性的复选框。

组 1:data-groupid= "1"data=multichoice="0"(10 个框)

组 2:data-groupid= "2"data=multichoice="0"(10 个框)

如何一次禁用一组中的所有框?

//function will catch any click on any checkbox with class=lvl
$('.lvl').click(function () {

   //check if box was checked
   if ($(this).is(":checked")) {

      //check if data-attribute is NOT a multi-choice
     if (!($(this).data("multichoice"))) {

        //disable all checkboxes that have the same group-id
        $(this).data("groupid") ... HELP HERE

     }
   }    
 });

最佳答案

由于您只想允许从组中选择 1 个项目,因此单选按钮将是更好的选择。

但是如果您仍然想使用复选框,那么您可以使用属性选择器进行过滤

$('.lvl').click(function() {
  //check if box was checked
  if (this.checked) {
    //check if data-attribute is NOT a multi-choice
    if (!$(this).data("multichoice")) {
      $('.lvl[data-groupid="' + $(this).data('groupid') + '"]').not(this).prop('checked', false);

    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="lvl" type="checkbox" data-groupid="1" data-multichoice="0" />
<input class="lvl" type="checkbox" data-groupid="1" data-multichoice="0" />
<input class="lvl" type="checkbox" data-groupid="1" data-multichoice="0" />
<br />
<input class="lvl" type="checkbox" data-groupid="2" data-multichoice="0" />
<input class="lvl" type="checkbox" data-groupid="2" data-multichoice="0" />
<input class="lvl" type="checkbox" data-groupid="2" data-multichoice="0" />
<input class="lvl" type="checkbox" data-groupid="2" data-multichoice="0" />

关于javascript - 根据数据属性启用或禁用复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33449735/

相关文章:

javascript - 将函数调用存储在数组中

javascript - var myArray =[], 名称;?

Javascript、正则表达式和 {n,m}

javascript - 在鼠标上输入在 Chrome 中行为不端

javascript - 将 jQuery SVG 转换为图像

jquery悬停效果消失

html - 如何使用 css-grids 使 div 居中?

html - 字段在 iOS 浏览器上显示不正确

javascript - Console.log 有没有办法命名发送的变量?

javascript - 在条形图上显示负值