I just created this function to change the page title after clicking the toggle button, but for some reason it gets stuck after clicking. I'm not sure what's wrong with this function, I wrote it in Jquery but it does the same thing even when coded in pure JavaScript. This is
in Jqueryfunction toggleButton() { console.log($('#toggle-employees').prop('checked')) if($('#toggle-employees').prop('checked', true)) { console.log("true"); $("#bodyTitle").html("Employees"); } else { console.log("false"); $("#bodyTitle").html("Roles"); }; }; <h1 id="bodyTitle" class="navbar-brand"></h1> <div class="form-check form-switch hidden" id="employee-toggler"> <input class="form-check-input" onclick="toggleButton()" type="checkbox" role="switch" id="toggle-employees"> <label class="form-check-label" for="toggle-employees">Employees</label> </div>
Here is a link to the function in JSPlayground, but that doesn't work either.
P粉5881526362024-04-04 21:12:02
==
or ===
to compare values. =
is used for assignment. Since the checked
attribute is a Boolean value, you can directly use document.getElementById('toggle-employees').checked
as a condition to check whether it is true
. checked
There is no need to set the property when it changes; it is completely redundant. function toggleButton() { var paragraph = document.getElementById("bodyTitle") console.log(document.getElementById('toggle-employees').checked) if (document.getElementById('toggle-employees').checked) { console.log("true"); paragraph.innerHTML = "Employees"; } else { console.log("false"); paragraph.innerHTML = "Roles"; } };