Home > Net >  Why does my checkbox get stuck and never return to default?
Why does my checkbox get stuck and never return to default?

Time:01-28

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" ></h1>

<div  id="employee-toggler">
    <input  onclick="toggleButton()" type="checkbox" role="switch" id="toggle-employees">
    <label  for="toggle-employees">Employees</label>
</div>

Here is a link to the function in JSPlayground that also doesn't work.

CodePudding user response:

  • 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  id="employee-toggler">
  <input  onclick="toggleButton()" type="checkbox" role="switch" id="toggle-employees">
  <label  for="toggle-employees">Employees</label>
</div>

CodePudding user response:

Fixed the fiddle for you. You were using "=" to check the isChecked condition. "=" is for assignment use "==" or "===" to compare.

  • Related