design/public/assets/js/checkboxBetter.js

53 lines
1.9 KiB
JavaScript
Raw Normal View History

2024-11-06 10:31:56 +00:00
document.addEventListener('DOMContentLoaded', function() {
// Function to update the parent class based on the checkbox/radio state
function updateParentClass(element) {
const parent = element.closest('.checkboxWrapper');
if (parent) {
if (element.checked) {
if (parent.classList.contains('checkboxWrapperFancy')) {
parent.classList.add('checkboxWrapperFancyActive');
}
} else {
if (parent.classList.contains('checkboxWrapperFancyActive')) {
parent.classList.remove('checkboxWrapperFancyActive');
}
}
}
}
// Function to handle radio button toggling
function handleRadioToggle(radio) {
const parent = radio.closest('.checkboxWrapper');
const radios = document.querySelectorAll('input.checkboxWrapperCheckRadio');
radios.forEach(r => {
const parentRadio = r.closest('.checkboxWrapper');
if (parentRadio && r !== radio) {
if (parentRadio.classList.contains('checkboxWrapperFancyActive')) {
parentRadio.classList.remove('checkboxWrapperFancyActive');
}
}
});
updateParentClass(radio);
}
// Select all checkboxes and radio buttons
const checkboxes = document.querySelectorAll('input.checkboxWrapperCheck[type="checkbox"]');
const radios = document.querySelectorAll('input.checkboxWrapperCheckRadio[type="radio"]');
// Add event listeners for checkboxes
checkboxes.forEach(checkbox => {
checkbox.addEventListener('change', function() {
updateParentClass(this);
});
});
// Add event listeners for radio buttons
radios.forEach(radio => {
radio.addEventListener('change', function() {
handleRadioToggle(this);
});
});
});