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

button text color not changing when I place the script inside another function

I want to change the text color of a button when I click on it using a function.
so I made a function for it which does not work.

code:

function correct(x) {
  document.getElementById("x").style.color = "green";
}

function wrong(y) {
  document.getElementById("y").style.color = "red";
}

function answer() {
  if (document.getElementById("p").innerHTML == "question 1") {
    correct(bt1);
    wrong(bt2);
  } else if (document.getElementById("p").innerHTML == "question 2") {
    correct(bt2);
    wrong(bt1);
  }
}
<p id="p">question 1</p>

<button id="bt1" onclick="answer()"> option 1</button>
<button id="bt2" onclick="answer()"> option 2</button>

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 :

You don’t need to call getElementById() to get the buttons to change. answer() passes the buttons directly, use the parameters.

function correct(x) {
  x.style.color = "green";
}

function wrong(y) {
  y.style.color = "red";
}

function answer() {
  if (document.getElementById("p").innerHTML == "question 1") {
    correct(bt1);
    wrong(bt2);
  } else if (document.getElementById("p").innerHTML == "question 2") {
    correct(bt2);
    wrong(bt1);
  }
}
<p id="p">question 1</p>

<button id="bt1" onclick="answer()"> option 1</button>
<button id="bt2" onclick="answer()"> option 2</button>

Note that use bt1 and bt2 as arguments takes advantage of the fact that element IDs automatically become global variables. This is not generally considered good style.

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