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>
6
Answers
You have your quotes backwards: the arguments to
correct
andwrong
should be quoted; the use of their parameters in those functions should not.I have added comments to your code directly. It seems that you may have put string markers at the wrong place
You don’t need to call
getElementById()
to get the buttons to change.answer()
passes the buttons directly, use the parameters.Note that use
bt1
andbt2
as arguments takes advantage of the fact that element IDs automatically become global variables. This is not generally considered good style.Since you are passing the button into the function but not using it, just change it to the following:
A better approach would be to use classes instead of IDs.
Firstly, your correct() and wrong() functions are trying to get elements with ID "x" and "y" respectively, but what i think you wanted is obtain the id from the function parameters.
Secondly, you’re sending to the correct() and wrong() functions, the IDs of the buttons as bt1 and bt2, but these are undefined, you should send them as strings "bt1", "bt2".
Others have already pointed out that your variables and the use of quotes is what is causing your problem, but beyond that, you really don’t need and shouldn’t be setting up dedicated functions just to change the color. Instead, you should set up CSS classes that define the possible "looks" you want and then simply add or remove the classes as needed.
Additionally, buttons aren’t really a good choice for answers to questions. This is what checkboxes and radio buttons are for. But, you can hide the checkboxes or radio buttons and use
label
elements to wrap them and show the labels, styled as buttons. This will give you the mutual exclusivity (in the case of radio buttons) that you desire.