Я хочу переключить переключатель с помощью простого Javascript с функцией. Но кажется, что цикл внутри этой функции не работает, поскольку он может определить только состояние по умолчанию. Оператор if-else работает, когда я пытаюсь вручную установить состояние ввода. Но, если я нажму на переключатель, ничего не произойдет. Для этого я использую Bootstrap 5 Beta. Открыт для любого лучшего предложения, если оно не требует фреймворка/библиотеки/дополнительного модуля, кроме JS-пакета начальной загрузки.
Вот мой html-код переключателя:
<div class = "form-check form-switch mx-3">
<input class = "form-check-input" type = "checkbox" id = "pricingSwitch">
</div>
И вот моя функция Javascript:
function pricingTable() {
console.info("Called")
var checkbox = document.getElementById('pricingSwitch')
var priceMonthly = document.getElementsByClassName("price-monthly")
var priceAnnual = document.getElementsByClassName("price-annual")
var durationMonth = document.getElementsByClassName("duration-month")
var durationYear = document.getElementsByClassName("duration-year")
console.info("Pre Loop")
for (var i = 0; i < priceMonthly.length; i++) {
console.info(checkbox.checked)
console.info(i)
if (checkbox.checked == true) {
priceMonthly[i].style.display = "none"
priceAnnual[i].style.display = "inline-block"
durationMonth[i].style.display = "none"
durationYear[i].style.display = "inline-block"
} else if (checkbox.checked == false) {
priceMonthly[i].style.display = "inline-block"
priceAnnual[i].style.display = "none"
durationMonth[i].style.display = "inline-block"
durationYear[i].style.display = "none"
}
}
}



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Итак, похоже, я не добавил слушателя для флажка. Это окончательный рабочий код
var checkbox = document.getElementById('pricingSwitch')
var priceMonthly = document.getElementsByClassName("price-monthly")
var priceAnnual = document.getElementsByClassName("price-annual")
var durationMonth = document.getElementsByClassName("duration-month")
var durationYear = document.getElementsByClassName("duration-year")
function checker(checked) {
checked ? showAnnual() : showMonthly()
}
function showAnnual() {
priceMonthly[0].style.display = "none"
priceAnnual[0].style.display = "inline-block"
durationMonth[0].style.display = "none"
durationYear[0].style.display = "inline-block"
}
function showMonthly() {
priceMonthly[0].style.display = "inline-block"
priceAnnual[0].style.display = "none"
durationMonth[0].style.display = "inline-block"
durationYear[0].style.display = "none"
}
checker(this.checked)
checkbox.addEventListener('change', function () {
checker(this.checked)
})