1

I'm still new to JavaScript but I wrote a small script that sends messages to a webhook. Which works great, but now I need to set some conditions to it before it may execute. The condition I wanted to set here was that the field "name" has to have a minimal length of 9 characters. I just can't find the fault in this if statement.

function json()
{
  if(document.getElementById('name').length >= 9)
  { 
    var msgJson = {
      "text": "success",
    };
  send(msgJson);
  }
}

Does anyone have the answer for me?
Thanks in advance!

3
  • Is this an input field? You need to chain a .value onto the end of the getElementById statement. Commented Oct 14, 2017 at 0:49
  • Yes it's a text input field in a form. So if I set it to .value, how can I chek the input character amount? Cause the input can be for example "peter" and than the condition of 9 characters is not met. Commented Oct 14, 2017 at 0:58
  • Martin's answer will explain it. Commented Oct 14, 2017 at 1:00

2 Answers 2

2

document.getElementById('name') returns HTML element reference. If you want to check the length of that input value (<input id="name">), then you need to use document.getElementById('name').value and check the length of it, like this:

function json() {
    var el = document.getElementById('name');
    if (el.value.length >= 9) {
        var msgJson = {
            "text": "succes",
        };
        send(msgJson);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

The getElementById() function returns an Element object (source). This has no .length property- so you are going to get an error.

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.