Shrijesh Siwakoti Shrijesh Siwakoti -4 years ago 56
HTML Question

Javascript to check if fields are entered for login

I'm trying to create a login page. I need to validate username and password but my js does not seem to work. I made it simpler now just for the sake to make it work. This is my html:

<script type="text/javascript" src = "js/checklogin.js"></script>
<h3>Already have an account?</h3>
<span id = "feedback"></span>
<form id = "login" action = "login.html" method = "post">
<label for = "name">User name:</label><br>
<input type = "text" name = "username " id = "username"><br>
<label for = "password">Password:</label><br>
<input type = "password" name = "password" id = "password"><br>

<input type="submit" value="Login">
</form>


And this is my js:

var elUsername = document.getElementById('username');
var elPassword = document.getElementById('password')
var elMsg = document.getElementById('feedback');
function checkFilled(length) {
if (length == "") {
elMsg.innerHTML = 'Please fill out this field';
} else {
document.getElementById("login").submit();
}
}
elUsername.addEventListener('blur', checkFilled(elUsername.value),false);
elPassword.addEventListener('blur', checkFilled(elPassword.value),false);


I still cannot make it to work. Also, how can i make it to appear as a pop up right on the textbox? Something that looks like this:
Error image

Answer Source

There's several issues with the code you had, so here's a complete example of the way I would do it (use the same HTML you already have). This works for me as tested in JSFiddle.

var elUsername = document.getElementById('username');
var elPassword = document.getElementById('password')
var elMsg = document.getElementById('feedback');
var elForm = document.getElementById('login');

function checkFilled() {
    if (elUsername.value == "" || elPassword.value == "") {
        elMsg.innerHTML = 'Please fill out this field';
        event.preventDefault();
    } else {
        elMsg.innerHTML = '';
    }
}

if (elForm.addEventListener) {
    elForm.addEventListener('submit', function() {
         checkFilled();
    }, false);
} else {
    elForm.attachEvent('onsubmit', function() {
         checkFilled();
    });
}

if (elUsername.addEventListener) {
    elUsername.addEventListener('blur', function() {
        checkFilled();
    }, false);
} else {
    elUsername.attachEvent('onblur', function() {
        checkFilled();
    });
}

if (elPassword.addEventListener) {
    elPassword.addEventListener('blur', function() {
        checkFilled();
    }, false);
} else {
    elPassword.attachEvent('onblur', function() {
        checkFilled();
    });
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download