Search code examples
jquerykeyuponkeyupjquery-focusout

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.


Solution

  • 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/