Sergi Sergi - 3 months ago 11
HTML Question

Simple buttons and Javascript function

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!";

}
}

Answer

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!";
  }

}