I have a main row and some other rows underneath that main row like this:
[checkbox] Main heading row
[checkbox] first child row
[checkbox] second child row
When I click on the child row, it should check the parent (main) row automatically. Problem is that it doesn't check it first time I click it. I have to check the first child row first, then uncheck the first child row and then check first child row again to get the parent (main) row get checked. I want the parent row get checked as soon as any of the child rows get checked.
I am using the following code
function checkbox_click(){
var n = event.srcElement;
if(n.parentElement.id == "row"){
n = n.parentElement;
}
if(n.id == "row"){
alert("ID: 1");
n.rs = n.parentElement;
if(this.multiSelect == 0){ // single select
alert("ID: 2");
n.all[0].checked = 1;
this.selectedRows = [ n ];
if(this.lastClicked && this.lastClicked != n){
this.lastClicked.all[0].checked = 0;
this.lastClicked.style.color = "000099";
this.lastClicked.style.backgroundColor = "";
}
} else {
alert("ID: 3");
n.all[0].click();
}
if(this.parentElement == pg.procs) {
alert("ID: 4");
var terminate = false;
var counter = 0;
if(n.className == "proc") {
alert("ID: 5");
z = n.nextSibling;
while(z.id == "row" && z.className != "proc" && !terminate) {
alert("ID: 6");
z.all[0].checked = 0;
z.style.backgroundColor = z.className == "w" ? "ffffff" : "ffffcc";
counter++;
if(counter > 1000) terminate = true;
z = z.nextSibling;
}
} else {
$(".row input").change(function() {
alert("ID: 7");
var $row= $(this).closest(".row");
var $main_row = $row.prev('.proc').length ? $row.prev('.proc') : $row.prevUntil(".proc").prev();
$main_row.find(":checkbox").attr("checked", function(i,attr) {
return $main_row.nextUntil('.proc').filter(':has(input:checked)').length ? "checked" : false;
});
});
$(".proc input").change(function() {
alert("ID: 8");
$(this).closest(".proc").nextUntil('.proc').children(':checkbox').attr('checked', this.checked);
});
}
If you want to check the parent checkbox when one of the child checkboxes is checked, I would suggest using a common class for the child checkboxes, and a unique id attribute for the parent checkbox (or store it as a variable).
Let's assume you have a structured HTML document that contains something like the following:
<div>
<input type="checkbox" name="ckparent" id="ckparent" />
<label for="ckparent">Parent</label>
<div>
<input type="checkbox" name="ckchild1" id="ckchild1" class="ckchild" />
<label for="ckchild1">Child 1</label>
</div>
<div>
<input type="checkbox" name="ckchild2" id="ckchild2" class="ckchild" />
<label for="ckchild2">Child 2</label>
</div>
</div>
You could then write the following jQuery code to check the parent checkbox when either of the children are checked:
$('input:checkbox.ckchild').click(function(event) {
var checked = $(this).is(':checked');
if (checked) {
$('#ckparent').attr('checked', true);
}
});
EDIT: The order in which the changed and clicked events are fired with regards to when the checked attribute is actually changed is dependent on the browser you are using -- which browsers are you targeting?
Related
abc.component.html:
<input class='alignedItem' type="checkbox" value="0" name={{cardProgram.id}}
[indeterminate] ="cardProgram.indeterminate" [checked] = "cardProgram.selected" [(ngModel)]='cardProgram.selected' [disabled]='(cardProgram.appId && !hasOtherAppsAssigned(cardProgram)) && (cardProgram.appId != getAppId())'
(click)='toggleCardProgram(cardProgram,cardProgram.selected)' />
<label class='fa col-1 showMore expand-indicator' [ngClass]="{'fa-plus': !rowIsExpanded(index),
'fa-minus': rowIsExpanded(index)}"
for='{{cardProgram.id}}'></label>
<input #hiddenAnimationInput class='h-0' type="checkbox" id='{{cardProgram.id}}'
(change)='rowClicked(index)' />
<!-- Hidden unless toggled -->
<div class='positionUp25'>
<ul>
<li *ngFor="let agentItem of cardProgram.agents">
<span class='col-12'>
<label class='offset-1TMP col-5'>
{{cardProgram.sys}}/{{cardProgram.prin}}/{{agentItem.agent}}
</label>
<label *ngIf=agentItem.application class='col-6' [ngClass]="{'text-disabled': agentItem.application && agentApp(agentItem) != getAppId()}">
{{agentItem.application.subAppName}}
</label>
<label *ngIf=!agentItem.application class='col-6'>
</label>
<input class='alignedItem ml-3' type="checkbox" name='{{cardProgram.sys}}{{cardProgram.prin}}{{agentItem.agent}}'
#{{cardProgram.sys}}{{cardProgram.prin}}{{agentItem.agent}}='ngModel'
[(ngModel)]='agentItem.selected' (click)='toggleAgent(agentItem, cardProgram)'
[disabled]='agentItem.application && agentApp(agentItem) != getAppId()' />
</span>
</li>
</ul>
</div>
cardPrograms.d.ts:
interface CardProgram {
.......
indeterminate:boolean;
checked:boolean;
......
}
indeterminate.directive.ts
import { Directive, ElementRef,Input } from '#angular/core';
#Directive({ selector: '[indeterminate]' })
export class IndeterminateDirective {
#Input()
set indeterminate(value)
{
this.elem.nativeElement.indeterminate=value;
}
constructor(private elem: ElementRef) {
}
}
abc.component.ts:
private toggleAgent(agent: Agent, cardProgram: CardProgram) {
debugger;
this.dirty = true;
console.log("selected" + agent.selected)
this.updateChangeValToObj(agent, cardProgram)
//agent.selected = !agent.selected;
if (agent.selected) {
agent.application = this.currentApplication();
} else {
agent.application = null;
// if we deselected, also unassign the app at the program level so it will reflect as 'Multiple Apps' state
cardProgram.application = null;
}
// this.togglecheckbox(cardProgram)
var x = 0;
cardProgram.agents.forEach(agent => {
if (agent.selected == true) {
++x;
console.log("inside agent.selected");
}
})
var length = cardProgram.agents.length;
if (x == 0) {
console.log("x is 0");
cardProgram.selected = false;
cardProgram.indeterminate =false;
}
else if (x == length) {
cardProgram.selected = true;
cardProgram.indeterminate =false;
}
else if (x > 0 && x < length) {
cardProgram.selected = false;
cardProgram.indeterminate =true;
}
else{
cardProgram.indeterminate =false;
cardProgram.selected = false;
}
}
When I select all the child check-boxes(agents), the parent should be checked and this works fine.
When all the agents are unchecked, and then I check one of the agents the indeterminate checkbox comes up which is fine.
Problem scenario: The problem comes when I check the parent checkbox which checks all the agents which is fine but when I uncheck one of the agents, that time indeterminate option should show which is not happening. It shows unchecked for parent.
In the abc.component.ts, I see the control goes into else if (x > 0 && x < length) and sets the cardProgram.indeterminate =true; but the indeterminate is not shown in the UI for the above mentioned problem scenario most of the times but strangely works sometimes.
edit: Ok i have come to know exactly how to recreate the issue: lets say there are three child check boxes (agents) and all are unchecked which makes the parent unchecked. Now when I check one of child (shows indeterminate) and then check the parent checkbox(checks all the agents) and uncheck one the child then indeterminate should come up which it does not
I have done something like this before, except it was done using a mat-table and mat-checkbox. But the core implementation remains the same.
I believe the requirement is to display a table or a list with checkboxes to select each row and a master checkbox to check/uncheck all of them, and also to display an indeterminate state when some of the rows are checked.
Something like this could be done using <mat-checkbox> which provides the same functionality as native <input type="checkbox">.
TS file
intialSelection: number[] = [];
allowMultiSelect = true;
selection = new SelectionModel<number>(this.allowMultiSelect, this.intialSelection);
// checks whether the number of selected elements is equal to the total number of elements in the list
isAllSelected() {
const numSelected = this.selection.selected.length;
const numRows = this.sourceData.length;
return numSelected == numRows;
}
// selects all rows if they are not selected; otherwise clears the selection
masterToggle(){
this.isAllSelected() ?
this.selection.clear() :
this.sourceData.forEach(row => this.selection.select(row.Id));
}
HTML File
<!-- The master checkbox -->
<mat-checkbox (change)="$event ? masterToggle() : null" [checked]="selection.hasValue() && isAllSelected()"
[indeterminate]="selection.hasValue() && !isAllSelected()">
<!-- Checkbox corresponding to individual rows -->
<mat-checkbox (click)="$event.stopPropagation()" (change)="$event ? selection.toggle(id) : null"
[checked]="selection.isSelected(id)">
Reference
https://material.angular.io/components/checkbox/overview
<input [indeterminate]="true" class="form-check-input" type="checkbox"/>
Code:
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript">
function displayquestion(a, ignore){
var b = a-1;
var currentInput = '';
var questions = document.getElementsByClassName("questionholder");
var showRequired = document.getElementById("requiredMessage");
if (document.querySelector('input.input' + b) !== null) {
var currentInput = document.querySelector('input.input' + b).value;
}
// Check if question should ignore inputs
if (ignore == 1) { // yes, ignore the inputs so move on to next question
console.log("path 1");
showRequired.style.display = "none";
for(var i=0; i < questions.length; i++) {
questions[i].style.display = "none";
}
var nextQuestion = document.getElementById("question" + a);
if(nextQuestion !== null) {
nextQuestion.style.display = "block";
}
} else { //no, don't ignore the inputs
if (currentInput == '') { // the input is blank so show error
console.log("path 2");
showRequired.style.display = "block";
} else { // the input is not blank so move on to next question
console.log("currentInput = " + currentInput);
showRequired.style.display = "none";
for(var i=0; i < questions.length; i++) {
questions[i].style.display = "none";
}
var nextQuestion = document.getElementById("question" + a);
if(nextQuestion !== null) {
nextQuestion.style.display = "block";
}
}
}
}
</script>
</head>
<body>
<div id="requiredMessage" style="display:none"><p>This field is required.</p></div>
<form id="TheForm" style="display:block;">
<div data-toggle="buttons" class="questionholder multiplechoice" id="question10" style="display:block">
<h5>Do you have a surname?</h5>
<input class="input10" type="radio" id="yes" name="sn" value="yes"><label for="relPPTsnyes"><p class="radioChoice">Yes / Oui</p></label>
<input class="input10" type="radio" id="no" name="sn" value="no"><label for="relPPTsnno"><p class="radioChoice">No / Non</p></label><br>
<a class="text2button radio" onclick="displayquestion(11)">Next</a>
</div>
</form>
</body>
</html>
I have issues with my javascript function, which works as intended with input text fields, but does not with radio buttons.
In short, I have a div that contains a pair of radio buttons and a next button. When the user click next, the function displayquestion(a) fires.
The function checks currentInput to see if the input is blank. If it is blank, it shows an error message. If it is not blank, it hides the div.
With radio buttons however, currentInput is always returning "yes" whether nothing is selected, no is selected or yes is selected. Since it isn't blank, it hides the div.
The intended result should be that the error message displays until the user makes a selection. only when the user clicks next, it should hide the div.
So my question is, what is causing my issue and how can it be fixed?
jsfiddle
use :checked
var currentInput = document.querySelectorAll('input.input' + b + ':checked").value;
Radios and Checkboxes always return their value.
The first thing you must do is check if one of them is selected, then get the value of the selected one.
const inputs = document.querySelectorAll('input[type=checkbox]') // or type=radio
for (const input of inputs)
{
if (input.checked)
{
console.log(input.value)
}
}
Also, querySelector() can return the selected one directly, without the need to loop the node list.
const input = document.querySelector('input[type=checkbox]:checked') // or type=radio
if (input)
{
console.log(input.value)
}
you not checking whether the radio is checked or not.As a result document.querySelector returns the first radio with value = "yes" use :checked is querySelector
if (document.querySelector('input.input' + b + ':checked') !== null) {
currentInput = document.querySelector('input.input' + b + ':checked').value;
console.log(currentInput)
}
My solution:
if (document.querySelector('input.input' + b).type == "radio") { //this is a radio input
if (document.querySelector('input[type=radio]:checked')) { //a radio option is selected
showNext();
} else { // no radio option is selected so show error
showRequired.style.display = "block";
}
} else { // not a radio input
}
I want the checked checkboxes to be unchecked when clicking another button:
Below is the HTML
<input type="checkbox" name="checkb" id="Agent" value="Agent"> type=Agent
<br />
<input type="checkbox" name="checkb" id="Customer" value="Customer"> type=Customer
<br />
<input type="checkbox" name="checkb" id="Phone" value="Phone"> type=Phone
<br />
<input type="checkbox" name="checkb" id="ID_Card" value="ID_Card"> type=ID_Card
<br />
<input type=datetime id="Start_Date" value="" placeholder="Start_Date" />
<input type=datetime id="End_Date" value="" placeholder="End_Date" />
<button id="date">
Interval
</button>
On clicking of the Interval button if any checkboxes are checked they should get unchecked.
Below is the event listener for the Interval button:
var check1 = document.getElementById("Agent");
var check2 = document.getElementById("Customer");
var check3 = document.getElementById("Phone");
var check4 = document.getElementById("ID_Card");
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
if (check1.checked) {
var ischecked1 = check1.checked;
check1.checked != ischecked1;
}
if (check2.checked) {
var ischecked2 = check2.checked;
check2.checked != ischecked2;
}
if (check3.checked) {
var ischecked3 = check3.checked;
check3.checked != ischecked3;
}
if (check4.checked) {
var ischecked4 = check4.checked;
check4.checked != ischecked4;
}
});
}
Below code runs without any errors, but the boxes do not get unchecked if they are checked.
Below is the fiddle
Your statements are just evaluating as booleans, not performing assignments:
check1.checked != ischecked1; // this returns a boolean, doesn't do any assignment
You want to do this to toggle the checked state:
check1.checked = !ischecked1;
Same thing for other checkboxes.
There's also no need to create the extra variables, you can just do the toggling and reading directly:
check1.checked = !check1.checked;
Since you're only toggling checkboxes when they are checked, you can just directly set them to false as well.
if (check1.checked) check1.checked = false;
Instead of having if statements, you can use array iteration to do the toggling:
[check1, check2, check3, check4].forEach(check => {
if (check.checked) {
check.checked = false;
}
});
// or query the checkboxes directly and do the same
[...document.querySelectorAll('input[type="checkbox"]')].forEach(check => {
if (check.checked) {
check.checked = false;
}
});
Your mistake is in this line:
check1.checked != ischecked1;
This actually means "compare if check1.checked is not equal to ischecked1".
Most simple solution would be to remove the if statement and just do this:
check1.checked = !check1.checked
This means "set check1.checked to the opposite of check1.checked".
Since all checkboxes have the same name you could also collect all checkboxes by requesting them by name and use a loop to walk through them. A small example:
// Collect all checkboxes with a CSS selector that matches all input
// elements with a name attribute that's equal to "checkb"
var checkboxes = document.querySelectorAll('input[name="checkb"]');
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
// this is a for loop, it will run for as long as i
// is smaller than the amount of found checkboxes (checkboxes.length)
for(var i = 0; i < checkboxes.length; i++) {
// Get the checkbox from the checkboxes collection
// collection[i] means get item from collection with index i
var checkbox = checkboxes[i];
// Revert the .checked property of the checkbox
checkbox.checked = !checkbox.checked;
}
});
}
By the looks of it you just want to uncheck everything on click of button
you can just do this
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
document.getElementById("Agent").checked =
document.getElementById("Customer").checked =
document.getElementById("Phone").checked =
document.getElementById("ID_Card").checked = false;
});
}
I have a set of set of checkboxes on which I want to restrict to check maximum of one. If the choice needs to be changed then first checked ones need to be unchecked but maximum limit needs to be one.
Here is the jquery code.
$('#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);
})
);
Here, the above code is restricting only one checkbox to be checked but when I am trying to check other, they first are being checked and then unchecked. Where I am doing wrong ?
Here is the dynamically created 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 += ' <label style="font-weight: 600; color: #00467f !important;"><input type="checkbox" value=' + arrReportscheckBoxItems[i] + '>' + arrReportscheckBoxItems[i] + '</label>';
}
//Add Submit button here
reportscheckBoxhtml += ' <button type="button" id="SubmitReport" class="btn btn-primary">Submit</button>';
$('#ReportRow').html(reportscheckBoxhtml);
Try this: uncheck all other checkboxes except clicked one inside click event handler, like below
$('#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>
This line:
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
is saying you want to uncheck the checkbox. It's doing exactly what you tell it to do. Just a comment: Users may be confused since checkboxes are meant to check multiple selections. Radio buttons are designed for being able to select only one option.
you are returning false from the function when there is a checkbox already selected, which is preventing the checkbox selection.
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
Do something like this:
$('#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);
});
I want to check all the checkboxes upon checking the "Selectall" checkbox and vice versa if I select all the checkboxes one by one then the "Selectall" checkbox should be automatically get checked. If I uncheck any of it's child checkboxes then the "Select all" checkbox should also be unchecked.
In my code, all the things are working except one thing that
if I select all the checkboxes one by one then the "Selectall" checkbox should be automatically get checked. Can anyone help me in making this thing workable for me. For your reference I'm giving my file code (HTML and Javascript code) here, so that you could test on your local machine.:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function () {
$("#ckbCheckAll").click(function () {
$(".checkBoxClass").prop('checked', $(this).prop('checked'));
});
$(".checkBoxClass").change(function(){
if (!$(this).prop("checked")){
$("#ckbCheckAll").prop("checked",false);
}
});
});
</script>
</head>
<body>
<input type="checkbox" id="ckbCheckAll" /> Check All
<p id="checkBoxes">
<input type="checkbox" class="checkBoxClass" id="Checkbox1" />
<br />
<input type="checkbox" class="checkBoxClass" id="Checkbox2" />
<br />
<input type="checkbox" class="checkBoxClass" id="Checkbox3" />
<br />
<input type="checkbox" class="checkBoxClass" id="Checkbox4" />
<br />
<input type="checkbox" class="checkBoxClass" id="Checkbox5" />
<br />
</p>
</body>
</html>
You can check how many checkboxes are there and how many are checked:
$(".checkBoxClass").change(function(){
var all = $('.checkBoxClass');
if (all.length === all.filter(':checked').length) {
$("#ckbCheckAll").prop("checked", true);
} else {
$("#ckbCheckAll").prop("checked", false);
}
});
Not sure if all can be just $(this);
In addition to the selectAll checkbox I have experimented with adding selectRow and selectCol checkboxes to get the same effect for each row and column of the grid of checkboxes.
see http://jsfiddle.net/wf_bitplan_com/snpc2L34/29/
/**
* http://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-
* expression
* examples:
*
* var matches = getRegexMatches(/(dog)/, "dog boat, cat car dog");
* console.log(matches);
*
* var matches = getRegexMatches(/(dog|cat) (boat|car)/, "dog boat, cat car");
* console.log(matches);
*/
function getRegexMatches(regex, string) {
if(!(regex instanceof RegExp)) {
return "ERROR";
}
else {
if (!regex.global) {
// If global flag not set, create new one.
var flags = "g";
if (regex.ignoreCase) flags += "i";
if (regex.multiline) flags += "m";
if (regex.sticky) flags += "y";
regex = RegExp(regex.source, flags);
}
}
var matches = [];
var match = regex.exec(string);
while (match) {
if (match.length > 2) {
var group_matches = [];
for (var i = 1; i < match.length; i++) {
group_matches.push(match[i]);
}
matches.push(group_matches);
}
else {
matches.push(match[1]);
}
match = regex.exec(string);
}
return matches;
}
/**
* get the select_row or select_col checkboxes dependening on the selectType row/col
*/
function getSelectCheckboxes(selectType) {
var regex=new RegExp("select_"+selectType+"_");
var result= $('input').filter(function() {return this.id.match(regex);});
return result;
}
/**
* matrix selection logic
* the goal is to provide select all / select row x / select col x
* checkboxes that will allow to
* select all: select all grid elements
* select row: select the grid elements in the given row
* select col: select the grid elements in the given col
*
* There is a naming convention for the ids and css style classes of the the selectors and elements:
* select all -> id: selectall
* select row -> id: select_row_row e.g. select_row_2
* select col -> id: select_col_col e.g. select_col_3
* grid element -> class checkBoxClass col_col row_row e.g. checkBoxClass row_2 col_3
*/
$(document).ready(function () {
// handle click event for Select all check box
$("#selectall").click(function () {
// set the checked property of all grid elements to be the same as
// the state of the SelectAll check box
var state=$("#selectall").prop('checked');
$(".checkBoxClass").prop('checked', state);
getSelectCheckboxes('row').prop('checked', state);
getSelectCheckboxes('col').prop('checked', state);
});
// handle clicks within the grid
$(".checkBoxClass").on( "click", function() {
// get the list of grid checkbox elements
// all checkboxes
var all = $('.checkBoxClass');
// all select row check boxes
var rows = getSelectCheckboxes('row');
// all select columnn check boxes
var cols = getSelectCheckboxes('col');
// console.log("rows: "+rows.length+", cols:"+cols.length+" total: "+all.length);
// get the total number of checkboxes in the grid
var allLen=all.length;
// get the number of checkboxes in the checked state
var filterLen=all.filter(':checked').length;
// console.log(allLen+"-"+filterLen);
// if all checkboxes are in the checked state
// set the state of the selectAll checkbox to checked to be able
// to deselect all at once, otherwise set it to unchecked to be able to select all at once
if (allLen == filterLen) {
$("#selectall").prop("checked", true);
} else {
$("#selectall").prop("checked", false);
}
// now check the completeness of the rows
for (row = 0; row < rows.length; row++) {
var rowall=$('.row_'+row);
var rowchecked=rowall.filter(':checked');
if (rowall.length == rowchecked.length) {
$("#select_row_"+row).prop("checked", true);
} else {
$("#select_row_"+row).prop("checked", false);
}
}
});
$('input')
.filter(function() {
return this.id.match(/select_row_|select_col_/);
}).on( "click", function() {
var matchRowColArr=getRegexMatches(/select_(row|col)_([0-9]+)/,this.id);
var matchRowCol=matchRowColArr[0];
// console.log(matchRowCol);
if (matchRowCol.length==2) {
var selectType=matchRowCol[0]; // e.g. row
var selectIndex=matchRowCol[1]; // e.g. 2
// console.log(this.id+" clicked to select "+selectType+" "+selectIndex);
// e.g. .row_2
$("."+selectType+"_"+selectIndex)
.prop('checked', $("#select_"+selectType+"_"+selectIndex).prop('checked'));
}
});
});
Use jQuery( ":checkbox" )
Maybe you can look # selectors of jquery http://api.jquery.com/category/selectors/
//----------Select AllCheckBoxes Begin ------------------------
function toggleChkBox() {
$('#tblPermissionDetails td input:checkbox').prop('checked', $('#chkSelectAll')[0].checked);
}
//----------Select AllCheckBoxes End --------------------------
//----------Check/Uncheck SelectAll checkbox based on other checkboxes Begin----------------
$('#tblPermissionDetails td input:checkbox').change(function() {
if (!$(this).prop("checked")) {
$("#chkSelectAll").prop("checked", false);
} else {
var PermissionList = [];
var PermissionListChecked = [];
$('#tblPermissionDetails td input:checkbox').each(function() {
PermissionList.push(this.name);
})
$('#tblPermissionDetails td input:checkbox:checked').each(function() {
PermissionListChecked.push(this.name);
})
if (PermissionList.length == PermissionListChecked.length) {
$("#chkSelectAll").prop("checked", true);
}
}
});
//----------Check/Uncheck SelectAll checkbox based on other checkboxes End------------------
<table class="table table-striped" id="tblPermissionDetails">
<thead>
<tr>
<th>Sl.No</th>
<th>Permission</th>
<th>Description</th>
<th><input type="checkbox" id="chkSelectAll" onclick="toggleChkBox();" />(Select All)</th>
</tr>
</thead>
<tbody>
#{ int i = 1; List
<FDSApp.Models.RolePermissionDetailsModel> permissionModel = Model; foreach (var item in permissionModel) {
<tr>
<td>#i</td>
<td>#item.PermissionName</td>
<td>#item.Description</td>
<td>#Html.CheckBox(#item.PermissionId.ToString(), #item.IsEnabled == 0 ? false : true)</td>
</tr>
i = i + 1; } }
</tbody>
</table>