2016-08-24 81 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); 
});