Tengo un campo de entrada y le agregué una cuenta regresiva de caracteres a través de Vanilla Javascript. El usuario puede agregar un máximo de 60 caracteres y el contador muestra cuántos caracteres quedan mientras escribe.
Cuando el campo de entrada está vacío, muestra que quedan 60 caracteres. Sin embargo, cuando ya hay un valor en el campo (cuando no está escribiendo), muestra que quedan 60 caracteres. Por lo tanto, no está contando la cantidad de caracteres del valor. Solo lo quita de los 60 cuando hago clic en el campo de entrada y empiezo a escribir.
Si hay un valor en el campo, ¿cómo puedo asegurarme de que sus caracteres se deduzcan automáticamente de la longitud máxima de caracteres?
Aquí está mi código:
const POST_TITLE = document.getElementById("post_title"); const MAX_LENGTH = 60; const CHARS = document.getElementById("chars"); function countCharacters() { let enteredChars = POST_TITLE.value.length; let charsLeft = MAX_LENGTH - enteredChars; if(charsLeft > 35) { CHARS.textContent = charsLeft + " characters remaining. Please add more characters for better SEO."; CHARS.style.color = "red"; } else if(charsLeft > 10) { CHARS.textContent = charsLeft + " characters remaining. Almost there! Just add a few more characters to have a great SEO title."; CHARS.style.color = "orange"; } else { CHARS.textContent = charsLeft + " characters remaining. Awesome! Between 50-60 characters is a great SEO title."; CHARS.style.color = "green"; } if(POST_TITLE.value.length == '') { CHARS.style.color = "black"; CHARS.textContent = charsLeft + " characters remaining. Please add a meta title."; } } POST_TITLE.addEventListener("keyup", countCharacters); <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/> <div class="container"> <form action="#" class="mt-4"> <div class="mb-3"> <label for="post_title" class="form-label">Post title</label> <input type="text" class="form-control" id="post_title" minlength="5" maxlength="60" value="some value"> <span id="chars">60 characters remaining. Please add a meta title.</span> </div> </form> </div>Así que aquí ya agregué un valor al campo de entrada para que pueda ver que cuando se carga la página no cuenta los caracteres del valor. Probé diferentes eventos en lugar del teclado, como la entrada, pero no funcionó.
Como se menciona en la sección de comentarios, simplemente llamar a countCharacters(); función bajo su alcance, activará el evento que busca.
Tenga en cuenta que los espacios en blanco aquí cuentan como caracteres.
const POST_TITLE = document.getElementById("post_title"); const MAX_LENGTH = 60; const CHARS = document.getElementById("chars"); function countCharacters() { let enteredChars = POST_TITLE.value.length; let charsLeft = MAX_LENGTH - enteredChars; if(charsLeft > 35) { CHARS.textContent = charsLeft + " characters remaining. Please add more characters for better SEO."; CHARS.style.color = "red"; } else if(charsLeft > 10) { CHARS.textContent = charsLeft + " characters remaining. Almost there! Just add a few more characters to have a great SEO title."; CHARS.style.color = "orange"; } else { CHARS.textContent = charsLeft + " characters remaining. Awesome! Between 50-60 characters is a great SEO title."; CHARS.style.color = "green"; } if(POST_TITLE.value.length == '') { CHARS.style.color = "black"; CHARS.textContent = charsLeft + " characters remaining. Please add a meta title."; } } countCharacters(); POST_TITLE.addEventListener("keyup", countCharacters); <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/> <div class="container"> <form action="#" class="mt-4"> <div class="mb-3"> <label for="post_title" class="form-label">Post title</label> <input type="text" class="form-control" id="post_title" minlength="5" maxlength="60" value="some value"> <span id="chars">60 characters remaining. Please add a meta title.</span> </div> </form> </div>