2

I'm completely new to JavaScript, and don't know why this isn't working. When I click on the input box, and type in less than 5 characters, i want a message to display. The message is simply not showing. Source code: https://jsfiddle.net/015por64/

<html>
    <body>
    <form id="form>">
        <input id="input">
        <div id="text"> Test </div>
        </input>
        </form>   
    </body>
</html>

<script>
function checkUserName(e, minLength) {
  var username = document.getElementById("input");
  var usernameLength = username.textContent;
    if (usernameLength.value.length < 5) {
        msg = "Your username must consist of at least five characters."
    };
    else {
        msg = "";
        text.innerHTML=msg
    };
}
var text = document.getElementById("text");
text.addEventListener("blur", function(e) {checkUserName(e, 5)}, false)
</script>

3
  • 1
    For input elements you should read the value property instead of textContent. Also note that input is a void element and it doesn't have an ending tag. Commented Aug 6, 2017 at 22:05
  • Thanks, but even when I change textContent to value, it doesn't work. Commented Aug 6, 2017 at 22:07
  • Why are you listening to blur event of the div element? You should listen to keyup event of the input. Commented Aug 6, 2017 at 22:09

2 Answers 2

1

Few issues with your code:

  1. you need to attach the event to #input and not the div#text.
  2. you need to read value of #input and not textcontent
  3. ; after if is wrong because then else will give syntax error.

<html>
    <body>
    <form id="form>">
        <input id="input">
        <div id="text"> Test </div>
        </input>
        </form>   
    </body>
</html>

<script>
function checkUserName(e, minLength) {
  var username = document.getElementById("input");
  var usernameLength = username.value;
    if (usernameLength.length < 5) {
        msg = "Your username must consist of at least five characters.";
        text.innerHTML=msg;
    }else {
        msg = "";
        text.innerHTML=msg;
    };
}
var text = document.getElementById("text");
document.getElementById('input').addEventListener("blur", function(e) {checkUserName(e, 5);}, false)
</script>

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

1 Comment

Thanks, this fixed it! Apparantly, I can't accept the answer in for 7 minutes, but I will once i can. Thanks again :)
0

It should be the input where you have to put the blur event listener.

var input = document.getElementById("input");

And since you have no use for text outside the function, better define it inside.

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.