Muiter
Muiter

Reputation: 1520

Determine getElementById length of input

I am using if (document.getElementById('bedrijfsnaam').value == false) to check if an input field has a value. How to check if it has more then 5 characters?

Upvotes: 1

Views: 8748

Answers (4)

adel.N
adel.N

Reputation: 31

if (document.getElementById("id").value.length > 5) 

THIS IS THE BEST SOLUTION BUT : if you are using VSCODE be careful of the capital V in value added while typing.

Upvotes: 0

P.S.
P.S.

Reputation: 16384

Very simple, just use .length:

if (document.getElementById('bedrijfsnaam').value.length > 5) {
  // do stuff
}

And here is the simple example with .value.length:

var checkLength = function () {
  if (document.getElementById('bedrijfsnaam').value.length > 5) {
    document.getElementById('more').setAttribute('style', 'display: block');
    document.getElementById('less').setAttribute('style', 'display: none');
  } else {
    document.getElementById('more').setAttribute('style', 'display: none');
    document.getElementById('less').setAttribute('style', 'display: block');
  }
}
<input id="bedrijfsnaam" onkeyup="checkLength()">

<p id="more">Input value length is more then 5</p>
<p id="less">Input value length is less or equal to 5</p>

Upvotes: 3

Muhammad
Muhammad

Reputation: 7324

In javasscript if a string is empty it is evaluated as false and for length you can use its length property

var inp = document.getElementById('bedrijfsnaam').value;
if (inp && inp.length > 5){
  // do something
}

Upvotes: 0

SKSpall
SKSpall

Reputation: 192

Say you are checking for both conditions together:

if (document.getElementById('bedrijfsnaam').value == false && document.getElementById('bedrijfsnaam').value.length>5)

length is a property of string that returns the number of characters in the string.

As document.getElementById('bedrijfsnaam').value will always return a string, you can easily calculate its length using this property.

Upvotes: 0

Related Questions