I'm trying to have some buttons and a message displaying depending on the user choice, right now only "correct" shows no matter the choice, what's wrong with my code?:
HTML:
<button id = "dec12" onclick="clickF1()"> December 12 <br> 2014 </button>
<button id = "nov13" onclick="clickF1()"> November 13 <br> 2014 </button>
<button id = "dec15" onclick="clickF1()"> December 15 <br> 2014 </button>
<h2 id ="output1"></h2>
Javascript:
function clickF1() {
var dec12 = document.getElementById("dec12");
var nov13 = document.getElementById("nov13");
var dec15 = document.getElementById("dec15");
if ("dec12") {
document.getElementById("output1").innerHTML = "Correct!";
} else if ("nov13") {
document.getElementById("output1").innerHTML = "Way off!";
} else if ("dec15") {
document.getElementById("output1").innerHTML = "Close but nope!";
}
}
2 Answers 2
Your if statements are always true, because a literal string always exists. (It is always "truthy" in JavaScript.) Even if you remove the quotes and just check the variables, they'd still always be true because those variables always exist.
It sounds like you just want to know which element was clicked. Have the element pass an identifier into the function. Something like this:
<button id = "dec12" onclick="clickF1('dec12')"> December 12 <br> 2014 </button>
<button id = "nov13" onclick="clickF1('nov13')"> November 13 <br> 2014 </button>
<button id = "dec15" onclick="clickF1('dec15')"> December 15 <br> 2014 </button>
Then check that value in the function:
function clickF1(day) {
if (day == "dec12") {
document.getElementById("output1").innerHTML = "Correct!";
} else if (day == "nov13") {
document.getElementById("output1").innerHTML = "Way off!";
} else if (day == "dec15") {
document.getElementById("output1").innerHTML = "Close but nope!";
}
}
1 Comment
Your clickF1 function is always running the same code. You should separate buttons by passing some variable when clicked.
For example, You can pass button, and then analyze it's id, like this:
HTML:
<button id = "dec12" onclick="clickF1(this)"> December 12 <br> 2014 </button>
<button id = "nov13" onclick="clickF1(this)"> November 13 <br> 2014 </button>
<button id = "dec15" onclick="clickF1(this)"> December 15 <br> 2014 </button>
Javascript:
function clickF1(button) {
var id = button.id;
if (id == "dec12") {
document.getElementById("output1").innerHTML = "Correct!";
} else if (id == "nov13") {
document.getElementById("output1").innerHTML = "Way off!";
} else if (id == "dec15") {
document.getElementById("output1").innerHTML = "Close but nope!";
}
}
if ("dec12")... a string is "truthy" - so that's always true