2016-08-24 4 views
0

最大1つまでチェックするように制限する一連のチェックボックスがあります。選択肢を変更する必要がある場合は、最初にチェックされたものをチェックする必要がありますが、最大限を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を提供します。

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

はこのようなものですか? –

+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; 
     } 

は、チェックボックスをオフにしたいと言っています。それはあなたがするように言うことを正確にしています。単なるコメント:チェックボックスは複数の選択をチェックするため、ユーザーは混乱するかもしれません。ラジオボタンは、1つのオプションのみを選択できるように設計されています。

0

の下にあなたが関数から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); 
}); 
関連する問題