Why are my checkboxes still stuck and unable to return to their default values?
P粉288069045
P粉288069045 2024-04-04 00:14:23
0
1
393

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 Jquery
function 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粉288069045
P粉288069045

reply all(1)
P粉588152636
  • Use == 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";
  }
};

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!