show div if field value matches a string

I need help with this, I want a div to show up when a user types in the correct value for a field e.g. ("ThePassword"). Here's what I have so far:

<input type="text" name="vip-code" id="vipcode" value="" />
<div id="container" style="display:none;"></div>

<script>
$(function () {
var validcode = "ThePassword";
$("#vipcode").focusout(function () {
    $(this).keyup(function () {
        var code = $(this).val();
        if (this === validcode) {
            $("#container").css("display", "block");
        } else {
            $("#container").css("display", "none");
        }
    });
});
});
</script>

Any ideas?

Thanks in advance.

Upvotes: 1

Views: 1240

Answers (2)

chris vdp
chris vdp

Reputation: 2842

In your code you only bind to the keyup event once the vipcode input loses focus, so there is a good chance that the keyup event will never be fired. It's also worth stating that hardcoding a password on the client side is very bad practice as it is a huge security flaw.

<input type="text" name="vip-code" id="vipcode" value="" />
<div id="container" style="display:none;"></div>

<script>
  $(function () {
    var validcode = "ThePassword";
    $("#vipcode").keyup(function () {
        var code = $(this).val();
        if (code === validcode) {
            $("#container").show();
        } else {
            $("#container").hide();
        }
    });
  });
</script>

http://jsfiddle.net/uuy6ovf6/2/

Upvotes: 0

Jordi Castilla
Jordi Castilla

Reputation: 27003

Not sure if handle keyup event is correct, but problem is: you're comparing validcode with the input field vip-code instead code variable...

if (code === validcode) {
    $("#container").css("display", "block");
} else {
    $("#container").css("display", "none");
}

Upvotes: 2

Related Questions