Start the length count from 1

Asked

Viewed 57 times

0

I’m starting to learn Javascript, and would like someone to help me solve the following problem: I made a simple character counter but it starts counting from 0, is there a way to start counting from 1?

<!DOCTYPE html>
<html lang="pt-br">
  <head>
    <title>Título da página</title>
    <meta charset="utf-8">
  </head>
  <body>
   <input type="text" onkeypress="contador()">
   <p>
     
   </p>
   <script>
    function contador(){
      var c = document.getElementsByTagName("input")
      var result = c[0].value.length
  
      var cont = document.getElementsByTagName("p")
      cont[0].innerText = result
}
   </script>
  </body>
</html>

2 answers

0

For an empty string, length is 0. When you call the "counter" function and there is no character inserted, you must return 0, unless you have a character not visible in the field, such as a space. If there is a need, you can add +1 to the length:

var result = c[0].value.length + 1;

0

Just put + 1 after the cont[0].innerText = result then the counter function would be:

function contador() {
        var c = document.getElementsByTagName("input")
        var result = c[0].value.length

        var cont = document.getElementsByTagName("p")
        cont[0].innerText = result + 1
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.