2016-08-24 80 views
0

我有一组复选框,我想限制在其中检查最多一个复选框。如果需要更改选择,则首先选中的选项需要取消选中,但最大限制必须为1。 这里是jQuery代码。复选框检查事件没有得到阻止

$('#ReportRow').on('click', 'input[type="checkbox"]', (function (event) { 
alert("Hi"); 
var checkedReportValues = $('#ReportRow input:checkbox:checked').map(function() { 
      return this.value; 
      }).get(); 

      if ($("#ReportRow input:checkbox:checked").length > 1) { 
        return false; 
      } 
      alert(checkedReportValues); 
}) 
); 

这里,上面的代码被限制只有一个被选中的复选框,但是当我试图检查等,他们首先被检查,然后选中。我在哪里做错了?

这里是动态创建的HTML。

//Add Code to Create CheckBox dynamically by accessing data from Ajax for the application selected above 
      var Reports = " User, Admin, Detail, Summary"; 
      var arrReportscheckBoxItems = Reports.split(','); 
      var reportscheckBoxhtml = '' 
      for (var i = 0; i < arrReportscheckBoxItems.length; i++) { 
       reportscheckBoxhtml += '&nbsp;&nbsp;&nbsp;&nbsp;<label style="font-weight: 600; color: #00467f !important;"><input type="checkbox" value=' + arrReportscheckBoxItems[i] + '>' + arrReportscheckBoxItems[i] + '</label>'; 
      } 

      //Add Submit button here 
      reportscheckBoxhtml += '&nbsp;&nbsp;&nbsp;&nbsp;<button type="button" id="SubmitReport" class="btn btn-primary">Submit</button>'; 

      $('#ReportRow').html(reportscheckBoxhtml); 
+0

提供您的HTML? –

+1

'如果选择需要改变,那么首先选中的选项需要取消选中,但最大限制必须是1。'使用'' –

+0

@MayankPandey添加了HTML – Lara

回答

2

试试这个:取消除点击一个所有其他复选框单击事件处理程序中,如下面

$('#ReportRow').on('click', 'input[type="checkbox"]',function(){ 
 
    $('#ReportRow input[type="checkbox"]').not(this).prop("checked",false); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="ReportRow"> 
 
<input type="checkbox">one 
 
    <input type="checkbox">Two 
 
    <input type="checkbox">Three 
 
    <input type="checkbox">Four 
 
</div>

0

这条线:

if ($("#ReportRow input:checkbox:checked").length > 1) { 
       return false; 
     } 

是说要取消选中该复选框。它正在做你说的要做的事情。只是一个评论:用户可能会感到困惑,因为复选框旨在检查多个选择。单选按钮被设计为能够仅选择一个选项。

0

你从函数返回false,如果已经有选择复选框,这阻止了复选框的选择。

if ($("#ReportRow input:checkbox:checked").length > 1) { 
        return false; 
      } 

做这样的事情:

$('#ReportRow').on('click', 'input[type="checkbox"]', (function (event) { 
    alert("Hi"); 
    var curCheckBox = this; 
    $('#ReportRow').find('input[type="checkbox"]').each(function() { 
     if(this === curCheckBox) 
      $(this).attr("checked",true); 
     else 
      $(this).attr("checked",false); 
    }); 
    alert(checkedReportValues); 
});