Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

If and Else JavaScript.

Hello! I am just making a little quiz to test my JavaScript skills. It is working okay but you just can't be correct for some reason, or the answer is always incorrect... The code is below any help is appr.

<script>
function check(){
    var answerMsg = document.getElementById('facebook');
    var answ = document.getElementById('q');

    if(answ == "Mark Zuckerberg"){
        answerMsg.innerHTML = "Correct: The answer was Mark Zuckerberg.";
      } else{
        answerMsg.innerHTML = "Incorrect: The answer was Mark Zuckerberg";
      }
}
</script>
<form>
Who invented Facebook? <input type="text" id="q"/><br /><br />
    <p id="facebook"></p>
    <input type="button" value="Submit" onclick="check();"/>
</form>
Aaron Martone
Aaron Martone
3,290 Points

I'm a believer of "Better to teach a man to fish than give him one." If you start to develop some troubleshooting steps, you may have seen this issue before needing to post. You can use console.log() to output variable values. If your code was constantly evaluating to the else clause, a log of their values would have revealed you were pointing to an element rather than its value.

2 Answers

Aaron Martone
Aaron Martone
3,290 Points

Start dumping and inspecting your variables. Look at what answ (poor variable naming, btw) is. You're not pointing it to the value of the q element, as you intend to. You're simply pointing it to the element itself. That's why answ !== 'Mark Zuckerberg'.

Oh, okay I see what you mean. Thanks!

Bob McCarty
PLUS
Bob McCarty
Courses Plus Student 16,618 Points

Nils,

The code sets the var answ to the element, not the element's value. Try

var answ = document.getElementById('q').value;

Bob

Okay so I see what the problem was. Thanks Bob! I will check out mdn on the .value