menu-checkboxes.js
76 lines
| 1 | ( function () { |
| 2 | const NovaCheckBoxes = { |
| 3 | inputs: null, |
| 4 | popInputs: null, |
| 5 | |
| 6 | initialize: function () { |
| 7 | // Get all checkboxes in the "nova_menuchecklist-pop" |
| 8 | NovaCheckBoxes.popInputs = document.querySelectorAll( |
| 9 | '#nova_menuchecklist-pop input[type="checkbox"]' |
| 10 | ); |
| 11 | |
| 12 | // Get all checkboxes in the "nova_menuchecklist" and add event listeners |
| 13 | NovaCheckBoxes.inputs = document.querySelectorAll( |
| 14 | '#nova_menuchecklist input[type="checkbox"]' |
| 15 | ); |
| 16 | NovaCheckBoxes.inputs.forEach( input => { |
| 17 | input.addEventListener( 'change', NovaCheckBoxes.checkOne ); |
| 18 | input.addEventListener( 'change', NovaCheckBoxes.syncPop ); |
| 19 | } ); |
| 20 | |
| 21 | // If no checkboxes are checked, check the first one |
| 22 | if ( ! NovaCheckBoxes.isChecked() ) { |
| 23 | NovaCheckBoxes.checkFirst(); |
| 24 | } |
| 25 | |
| 26 | // Sync the state of the "pop" inputs |
| 27 | NovaCheckBoxes.syncPop(); |
| 28 | }, |
| 29 | |
| 30 | syncPop: function () { |
| 31 | NovaCheckBoxes.popInputs.forEach( popInput => { |
| 32 | const linkedInput = document.querySelector( `#in-nova_menu-${ popInput.value }` ); |
| 33 | popInput.checked = linkedInput ? linkedInput.checked : false; |
| 34 | } ); |
| 35 | }, |
| 36 | |
| 37 | isChecked: function () { |
| 38 | return Array.from( NovaCheckBoxes.inputs ).some( input => input.checked ); |
| 39 | }, |
| 40 | |
| 41 | checkFirst: function () { |
| 42 | const firstInput = NovaCheckBoxes.inputs[ 0 ]; |
| 43 | if ( firstInput ) { |
| 44 | firstInput.checked = true; |
| 45 | } |
| 46 | }, |
| 47 | |
| 48 | checkOne: function () { |
| 49 | const currentInput = this; |
| 50 | |
| 51 | // If the current checkbox is checked, uncheck all other checkboxes |
| 52 | if ( currentInput.checked ) { |
| 53 | NovaCheckBoxes.inputs.forEach( input => { |
| 54 | if ( input !== currentInput ) { |
| 55 | input.checked = false; |
| 56 | } |
| 57 | } ); |
| 58 | return; |
| 59 | } |
| 60 | const checklist = document.querySelector( '#nova_menuchecklist' ); |
| 61 | |
| 62 | // If at least one checkbox is still checked, uncheck the current one |
| 63 | if ( checklist.querySelectorAll( 'input[type="checkbox"]:checked' ).length > 0 ) { |
| 64 | currentInput.checked = false; |
| 65 | return; |
| 66 | } |
| 67 | |
| 68 | // Otherwise, check the first checkbox |
| 69 | NovaCheckBoxes.checkFirst(); |
| 70 | }, |
| 71 | }; |
| 72 | |
| 73 | // Initialize when the DOM is fully loaded |
| 74 | document.addEventListener( 'DOMContentLoaded', NovaCheckBoxes.initialize ); |
| 75 | } )(); |
| 76 |