Created
January 13, 2023 15:16
-
-
Save maximal/c604763e9f5ebaaeb4ed3fac8ba7eca4 to your computer and use it in GitHub Desktop.
TypeScript-модуль включающих/отключающих элементы чекбоксов
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Модуль включающих/отключающих различные элементы чекбоксов. | |
* | |
* @author MaximAL | |
* @since 2023-01-13 Первая версия | |
*/ | |
const DEFAULT_SELECTOR = 'input[type=checkbox][data-checkbox-enable-element]'; | |
/** | |
* Инициализировать включающие/отключающие различные элементы чекбоксов. | |
* Нужно создать чекбокс с атрибутом `data-checkbox-enable-element=".element-selector"`, | |
* где будет селектор элемента, которому этот чекбокс будет проставлять атрибут `disabled`. | |
* | |
* @example | |
* Создаём элементы в HTML: | |
* ```html | |
* <input type="checkbox" id="email-consent" value="1" required | |
* data-checkbox-enable-element="button[type=submit]" /> | |
* <button type="submit" class="btn btn-success">Отправка формы</button> | |
* ``` | |
* Инициализируем в Яваскрипте: | |
* ```js | |
* initCheckboxEnables(document); | |
* ``` | |
* Теперь при смене состояния чекбокса, будет меняться включенность/отключенность элемента (атрибут `disabled`). | |
*/ | |
export default function initCheckboxEnables(document: Document): void { | |
document.querySelectorAll(DEFAULT_SELECTOR).forEach( | |
(checkbox: HTMLInputElement) => initCheckboxEnable(checkbox, document) | |
); | |
} | |
export function initCheckboxEnable(checkbox: HTMLInputElement, document: Document): void { | |
const element: HTMLElement = document.querySelector(checkbox.getAttribute('data-checkbox-enable-element')); | |
if (!element) { | |
return; | |
} | |
setElementEnabled(element, checkbox.checked); | |
checkbox.addEventListener('input', (event: Event) => { | |
event.preventDefault(); | |
setElementEnabled(element, checkbox.checked); | |
}); | |
} | |
function setElementEnabled(element: HTMLElement, enabled: boolean): void { | |
if (enabled) { | |
element.removeAttribute('disabled'); | |
} else { | |
element.setAttribute('disabled', 'disabled'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment