I am working on an asp.net razor page. I face issue where I can’t select any checkbox checked except all.
If all checkbox checked then all checked check box it working correctly.
If all checkbox not checked then all checkbox not checked and it working correctly.
My issue when select any item not equal All then it will not checked if I select.
So how to solve this issue?
Code Snippet
$(document).on('change', '.classCheckbox', function(event) {
var allCheckbox = $('.classCheckbox[value="0"]');
var checkboxes = $('.classCheckbox').not(allCheckbox);
if (allCheckbox.prop('checked')) {
checkboxes.prop('checked', true);
} else {
checkboxes.prop('checked', false);
}
var selectedClassIds = [];
var selectedClassIdsValues = []; // Array to store selected values
$('.classCheckbox:checked').each(function() {
selectedClassIds.push($(this).val());
selectedClassIdsValues.push($(this).next('span').text());
});
if (selectedClassIds.length > 0) {
$.ajax({
url: '?handler=CheckedAccountClassName',
type: 'GET',
traditional: true,
data: {
classIds: selectedClassIds,
classIdsValues: selectedClassIdsValues
},
success: function(response) {
$('#subClassesList').empty();
$('#subClassesContainer').show();
var subClassesContainer = $('<div data-class-id="' + selectedClassIds + '"></div>');
$.each(response, function(i, item) {
$(subClassesContainer).append('<input type="checkbox" class="subclassCheckbox" name="selectedSubClasses" value="' + item.subClassAccountId + '" /> ' + item.subClassAccountName + '<br />');
});
$('#subClassesList').append(subClassesContainer);
}
});
}
})
label {
margin-right: 1rem;
}
<label><input type="checkbox" class="classCheckbox" value="0">All</label>
<label><input type="checkbox" class="classCheckbox" value="X">X</label>
<label><input type="checkbox" class="classCheckbox" value="Y">Y</label>
<label><input type="checkbox" class="classCheckbox" value="Z">Z</label>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
2
Answers
Something like this… ?
You can check if the checkbox which checked currently has value
0
depending on this select all checkbox or remove checked.Demo Code :