+ 4
How do I make the input box value a variable?
I have been trying to get this code to work so that when I input Kayla, it alerts me with correct. It's not giving me anything and when I add else it jyst gives me the incorrect alert which makes me think that the code doesn't know that it's suppose to see if the value entered into the box is equal to the variable correct . How can I get this working? https://code.sololearn.com/Wu37oB863SyV/?ref=app
4 Answers
+ 4
"if(answer=correct)"
^That's assigning the value of 'correct' to the variable 'answer.' It'll ALWAYS return true because of that. That's incorrect way of comparing variables.
+ 2
I can't believe it was that simple. I feel stupid. đ
+ 2
I corrected your code below and posted it for you. Basically, you declared the same variables a few times, so you want to remove all of those variables outside of the function. Your 'answer' variable is being assigned the element, but you're not using the methods of that element to obtain the value of the element for comparison against your 'correct' variable. For your input element, use the '.value' method to get its input value.
Hope that helps!
https://code.sololearn.com/WCxhVZOFCl4I/#js
function func(){
var answer=document.getElementById("password");
var button=document.getElementById("submit");
var correct="Kayla";
if(answer.value == correct){
alert("Correct!")
}
else{
alert("Incorrect")
}
}
+ 1
document.getElementById("password") give you the element reference, you need to access the "value" attribute to get the <input> value:
var answer=document.getElementById("password").value;
or:
if(answer.value==correct){
But you need also to get the element reference inside your function... else when the JS tab is executed, the reference doesn't exist and getElementById will return null ^^