Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a button affect a boolean value in html?

I’m still learning html and Javascript, so I’m not too good at it. I’m trying to make it so that when I press a button, some text switches from "On" to "Off" and vise versa.

function switch_status() {

  //Setting status to opposite
  if (status = "Turn Appearance Off:") {
    status = "Turn Appearance On:"
  };
  
  if (status = "Turn Appearance On:") {
    status = "Turn Appearance Off:"
  };
  
  //Printing it out
  status_print.innerHTML = status;
}

var status = "Turn Appearance Off:";
var status_print = document.getElementById("status_print");

//calling function
switch_status();
<h1 id="status_print">Turn Appearance On:</h1>
<button type="button" onclick="switch_status()">Click Me!</button>

As you can see, it’s supposed to switch from On to Off when I hit the button. But it doesn’t seem to work, help would much be appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here’s a slight adaptation of your code. el gets the target element, and is used to get the status and also to give it the newStatus once you’re finished updating the new value.

function switch_status() {
 let el = document.querySelector('#status_print');
 let status = el.innerHTML;
 let newStatus;
  //Setting status to opposite
  if (status === "Turn Appearance Off:") {
    newStatus = "Turn Appearance On:"
  };
  
  if (status === "Turn Appearance On:") {
    newStatus = "Turn Appearance Off:"
  };
  
  //Printing it out
  el.innerHTML = newStatus;
}
<h1 id="status_print">Turn Appearance On:</h1>
<button type="button" onclick="switch_status()">Click Me!</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading