1

So I have an issue where I need to make my code when the mouse leaves an input field and the input field is either empty or has less than 5 characters it outputs something

I have tried putting .value after the getelementbyid. Please know that I can't use a button to submit the form.

var username = document.getElementById('username');
var user_length = username.length;

username.onmouseout = function(){
    if(username == ""){
        alert('hi');
        // var username_value = 
        //document.getElementById("username_output");
        // username_value.innerHTML ="Please fill in your username!";
        // username_value.style.color = 'red';
    }

    else if(user_length < 5){
        alert('smaller than 5');
    }
    else{
        alert('else');
    }
};

Whenever the mouse leaves it should output something. For some reason it's only going in the else statement not the other statements

0

1 Answer 1

4

You're comparing the input itself (the DOM element, the result of document.getElementById('username')) with a string, not the input's value.

You want its value property:

if (username.value == "") {

But note that the user might type in a space, in which case the above would be false because " " is not equal to "". You can use trim to fix that:

if (username.value.trim() == "") {

Since empty strings are falsy¹, you can also save some typing:

if (!username.value.trim()) {

¹ "falsy" - Any JavaScript value that coerces to false when used as a boolean is called a falsy value. The falsy values are 0, "", NaN, null, undefined, and of course, false; all other values are truthy.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.