I am developing a character count for my textarea on this website. Right now, it says NaN because it seems to not find the length of how many characters are in the field, which at the beginning is 0, so the number should be 500. In the console in chrome developer tools, no error occur. All of my code is on the site, I even tried to use jQuery an regular JavaScript for the character count for the textarea field, but nothing seems to work.
Please tell me what I am doing wrong in both the jQuery and the JavaScript code I have in my contact.js file.
$(document).ready(function() {
var tel1 = document.forms["form"].elements.tel1;
var tel2 = document.forms["form"].elements.tel2;
var textarea = document.forms["form"].elements.textarea;
var clock = document.getElementById("clock");
var count = document.getElementById("count");
tel1.addEventListener("keyup", function (e){
checkTel(tel1.value, tel2);
});
tel2.addEventListener("keyup", function (e){
checkTel(tel2.value, tel3);
});
/*$("#textarea").keyup(function(){
var length = textarea.length;
console.log(length);
var charactersLeft = 500 - length;
console.log(charactersLeft);
count.innerHTML = "Characters left: " + charactersLeft;
console.log("Characters left: " + charactersLeft);
});​*/
textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);
});
function checkTel(input, nextField) {
if (input.length == 3) {
nextField.focus();
} else if (input.length > 0) {
clock.style.display = "block";
}
}
function textareaLengthCheck(textarea) {
var length = textarea.length;
var charactersLeft = 500 - length;
count.innerHTML = "Characters left: " + charactersLeft;
}
This question is related to
javascript
jquery
html
textarea
charactercount
This solution will respond to keyboard and mouse events, and apply to initial text.
$(document).ready(function () {_x000D_
$('textarea').bind('input propertychange', function () {_x000D_
atualizaTextoContador($(this));_x000D_
});_x000D_
_x000D_
$('textarea').each(function () {_x000D_
atualizaTextoContador($(this));_x000D_
});_x000D_
});_x000D_
_x000D_
function atualizaTextoContador(textarea) {_x000D_
var spanContador = textarea.next('span.contador');_x000D_
var maxlength = textarea.attr('maxlength');_x000D_
if (!spanContador || !maxlength)_x000D_
return;_x000D_
var numCaracteres = textarea.val().length;_x000D_
spanContador.html(numCaracteres + ' / ' + maxlength);_x000D_
}
_x000D_
span.contador {_x000D_
display: block;_x000D_
margin-top: -20px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<textarea maxlength="100" rows="4">initial text</textarea>_x000D_
<span class="contador"></span>
_x000D_
var maxchar = 10;_x000D_
$('#message').after('<span id="count" class="counter"></span>');_x000D_
$('#count').html(maxchar+' of '+maxchar);_x000D_
$('#message').attr('maxlength', maxchar);_x000D_
$('#message').parent().addClass('wrap-text');_x000D_
$('#message').on("keydown", function(e){_x000D_
var len = $('#message').val().length;_x000D_
if (len >= maxchar && e.keyCode != 8)_x000D_
e.preventDefault();_x000D_
else if(len <= maxchar && e.keyCode == 8){_x000D_
if(len <= maxchar && len != 0)_x000D_
$('#count').html(maxchar+' of '+(maxchar - len +1));_x000D_
else if(len == 0)_x000D_
$('#count').html(maxchar+' of '+(maxchar - len));_x000D_
}else_x000D_
$('#count').html(maxchar+' of '+(maxchar - len-1)); _x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea id="message" name="text"></textarea>
_x000D_
$(document).ready(function(){
$('#characterLeft').text('140 characters left');
$('#message').keydown(function () {
var max = 140;
var len = $(this).val().length;
if (len >= max) {
$('#characterLeft').text('You have reached the limit');
$('#characterLeft').addClass('red');
$('#btnSubmit').addClass('disabled');
}
else {
var ch = max - len;
$('#characterLeft').text(ch + ' characters left');
$('#btnSubmit').removeClass('disabled');
$('#characterLeft').removeClass('red');
}
});
});
For those wanting a simple solution without jQuery, here's a way.
textarea and message container to put in your form:
<textarea onKeyUp="count_it()" id="text" name="text"></textarea>
Length <span id="counter"></span>
JavaScript:
<script>
function count_it() {
document.getElementById('counter').innerHTML = document.getElementById('text').value.length;
}
count_it();
</script>
The script counts the characters initially and then for every keystroke and puts the number in the counter span.
Martin
They say IE has issues with the input
event but other than that, the solution is rather straightforward.
ta = document.querySelector("textarea");_x000D_
count = document.querySelector("label");_x000D_
_x000D_
ta.addEventListener("input", function (e) {_x000D_
count.innerHTML = this.value.length;_x000D_
});
_x000D_
<textarea id="my-textarea" rows="4" cols="50" maxlength="10">_x000D_
</textarea>_x000D_
<label for="my-textarea"></label>
_x000D_
Here are two scenarios where the keyup
event will not get fired:
Use the HTML5 input
event instead for a more robust solution:
<textarea maxlength='140'></textarea>
JavaScript (demo):
const textarea = document.querySelector("textarea");
textarea.addEventListener("input", event => {
const target = event.currentTarget;
const maxLength = target.getAttribute("maxlength");
const currentLength = target.value.length;
if (currentLength >= maxLength) {
return console.log("You have reached the maximum number of characters.");
}
console.log(`${maxLength - currentLength} chars left`);
});
And if you absolutely want to use jQuery:
$('textarea').on("input", function(){
var maxlength = $(this).attr("maxlength");
var currentLength = $(this).val().length;
if( currentLength >= maxlength ){
console.log("You have reached the maximum number of characters.");
}else{
console.log(maxlength - currentLength + " chars left");
}
});
This code gets the maximum value from the maxlength
attribute of the textarea
and decreases the value as the user types.
<DEMO>
var el_t = document.getElementById('textarea');_x000D_
var length = el_t.getAttribute("maxlength");_x000D_
var el_c = document.getElementById('count');_x000D_
el_c.innerHTML = length;_x000D_
el_t.onkeyup = function () {_x000D_
document.getElementById('count').innerHTML = (length - this.value.length);_x000D_
};
_x000D_
<textarea id="textarea" name="text"_x000D_
maxlength="500"></textarea>_x000D_
<span id="count"></span>
_x000D_
textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);
You are calling textareaLengthCheck
and then assigning its return value to the event listener. This is why it doesn't update or do anything after loading. Try this:
textarea.addEventListener("keypress",textareaLengthCheck,false);
Aside from that:
var length = textarea.length;
textarea
is the actual textarea, not the value. Try this instead:
var length = textarea.value.length;
Combined with the previous suggestion, your function should be:
function textareaLengthCheck() {
var length = this.value.length;
// rest of code
};
Here is simple code. Hope it is working
$(document).ready(function() {_x000D_
var text_max = 99;_x000D_
$('#textarea_feedback').html(text_max + ' characters remaining');_x000D_
_x000D_
$('#textarea').keyup(function() {_x000D_
var text_length = $('#textarea').val().length;_x000D_
var text_remaining = text_max - text_length;_x000D_
_x000D_
$('#textarea_feedback').html(text_remaining + ' characters remaining');_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea id="textarea" rows="8" cols="30" maxlength="99" ></textarea>_x000D_
<div id="textarea_feedback"></div>
_x000D_
I found that the accepted answer didn't exactly work with textarea
s for reasons noted in Chrome counts characters wrong in textarea with maxlength attribute because of newline and carriage return characters, which is important if you need to know how much space would be taken up when storing the information in a database. Also, the use of keyup is depreciated because of drag-and-drop and pasting text from the clipboard, which is why I used the input
and propertychange
events. The following takes newline characters into account and accurately calculates the length of a textarea
.
$(function() {_x000D_
$("#myTextArea").on("input propertychange", function(event) {_x000D_
var curlen = $(this).val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length;_x000D_
_x000D_
$("#counter").html(curlen);_x000D_
});_x000D_
});_x000D_
_x000D_
$("#counter").text($("#myTextArea").val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<textarea id="myTextArea"></textarea><br>_x000D_
Size: <span id="counter" />
_x000D_
Source: Stackoverflow.com