skip to Main Content

I’ve just made this function to change my page title once the toggle button is clicked but for some reason it gets stuck once clicked. I’m not sure where I am going wrong with this function I have it written in Jquery but it does the same thing even when coded in pure JavaScript. Here it 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 that also doesn’t work.

2

Answers


    • Use == or === to compare values. = is for assignment. Since the checked property is a boolean, you can directly use document.getElementById('toggle-employees').checked as the condition to check if it is true.
    • There is no need to set the checked property when it changes; it is entirely 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";
      }
    };
    <p id="bodyTitle"></p>
    
    <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>
    Login or Signup to reply.
  1. Fixed the fiddle for you. You were using "=" to check the isChecked condition. "=" is for assignment use "==" or "===" to compare.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search