user7148024 user7148024 - 24 days ago 8
Javascript Question

Javascript value change TypeError zxcvbn

So I am trying to make a meter that determents if the password a user enters is strong using zxcvbn but although the code works on codepen, it throws a

TypeError: password is null
on my browser and does not update the meter as I type letters on the password input.

Code:

HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/zxcvbn/4.2.0/zxcvbn.js"></script>

<input class="form-control" type="password" id="password" />
<div id="pwd-container">
<meter max="4" id="password-meter"></meter>
</div>


Javascript:

var password = document.getElementById('password');
var meter = document.getElementById('password-meter');

password.addEventListener('input', function() {
var val = password.value;
var result = zxcvbn(val);

meter.value = result.score;
});

Answer

You probably put your JS code above HTML. Try this:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/zxcvbn/4.2.0/zxcvbn.js"></script>

    <input class="form-control" type="password" id="password"  />
    <div id="pwd-container">
        <meter max="4" id="password-meter"></meter>
    </div>

    <script type="text/javascript">

    var password = document.getElementById('password');
    var meter = document.getElementById('password-meter');

    password.addEventListener('input', function() {
        var val = password.value;
        var result = zxcvbn(val);

        meter.value = result.score;
    });

    </script>

</body>
</html>
Comments