Sara Tasic Sara Tasic - 1 month ago 11
HTML Question

html and javascript password: how to change display of an element if the password is correct?

I need to make a password protected image in HTML with help of Javascript, which means, if you enter a correct password, an image would appear.I'm a beginner, so I can't find any error in this. I don't even know if any if this code is well written, so I would be very thankful if you could help.

HTML:

<img src="..." id="smiley"/>
<form>
This picture is password protected<br>Enter a password:<br>
<input type="password" name="password" id="password">
<input type="button" onclick="funcPass( );" value="Ok">
</form>


JavaScript:

var password = getElementById("password").value;
function funcPass(password.value) {
if (password.value == "smiley")
{
document.getElementById("smiley").style.display = "block";
}
else
{
password.value = " ";
}
}


In CSS I changed image display property to none

Answer Source

Your code to get the password needs to be in the function itself. You're also getting the value twice (the value of the value). Try this:

function funcPass() {
    var password = document.getElementById("password").value;
    if (password == "In A Darkened Room")
    {
        document.getElementById("smiley").style.display = "block";
    }
    else
    {
        password = "";
    }
 }