0

I have to create a function to show the number of characters typed in the textarea. I think the code is ok, but I get an undefined error. Can you tell me why? Thanks.

<html>

<head>
  <style>
    textarea {
      width: 200px;
      height: 130px
    }
  </style>
</head>

<body>
  <textarea onkeypress="caractere()" name="numar"></textarea>
  <p>Number of characters typed: <span></span></p>

  <script>
    function caractere() {
      document.getElementsByTagName('span')[0].innerHTML = document.getElementsByName('numar')[0].length;
    }
  </script>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Daniel
  • 11
  • Use `value` i.e. `document.getElementsByTagName('span')[0].innerHTML = document.getElementsByName('numar')[0].value.length;` – Hassan Imam Apr 23 '18 at 07:13

1 Answers1

0

document.getElementsByName('numar')[0].length

getElementsByName returns an HTMLCollection. When you select [0], you're selecting the first element in the collection. HTML elements do not have a length property. You need to get the length of the value of the element:

<html>

<head>
  <style>
    textarea {
      width: 200px;
      height: 130px
    }
  </style>
</head>

<body>
  <textarea onkeypress="caractere()" name="numar"></textarea>
  <p>Number of characters typed: <span></span></p>

  <script>
    function caractere() {
      document.getElementsByTagName('span')[0].innerHTML = document.getElementsByName('numar')[0].value.length;
    }
  </script>

But there's not much sense using a method that returns a collection when you're only selecting a single element. Use querySelector instead:

document.querySelector('span').textContent =
  document.querySelector('[name="numar"]').value.length;
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320