How do I make the input box value a variable? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

27th Mar 2018, 5:42 PM
Babydoll Scripts
Babydoll Scripts - avatar
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.
27th Mar 2018, 5:52 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 2
I can't believe it was that simple. I feel stupid. 😑
27th Mar 2018, 5:49 PM
Babydoll Scripts
Babydoll Scripts - avatar
+ 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") } }
27th Mar 2018, 5:51 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 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 ^^
27th Mar 2018, 5:52 PM
visph
visph - avatar