Count textarea characters - javascript

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;
}

$("#textarea").keyup(function(){
$("#count").text($(this).val().length);
});
The above will do what you want. If you want to do a count down then change it to this:
$("#textarea").keyup(function(){
$("#count").text("Characters left: " + (500 - $(this).val().length));
});
Alternatively, you can accomplish the same thing without jQuery using the following code. (Thanks #Niet)
document.getElementById('textarea').onkeyup = function () {
document.getElementById('count').innerHTML = "Characters left: " + (500 - this.value.length);
};

⚠️ The accepted solution is outdated.
Here are two scenarios where the keyup event will not get fired:
The user drags text into the textarea.
The user copy-paste text in the textarea with a right click (contextual menu).
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");
}
});

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 help you
$(document).ready(function() {
var text_max = 99;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#textarea').keyup(function() {
var text_length = $('#textarea').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea" rows="8" cols="30" maxlength="99" ></textarea>
<div id="textarea_feedback"></div>

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');
var length = el_t.getAttribute("maxlength");
var el_c = document.getElementById('count');
el_c.innerHTML = length;
el_t.onkeyup = function () {
document.getElementById('count').innerHTML = (length - this.value.length);
};
<textarea id="textarea" name="text"
maxlength="500"></textarea>
<span id="count"></span>

I found that the accepted answer didn't exactly work with textareas 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() {
$("#myTextArea").on("input propertychange", function(event) {
var curlen = $(this).val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length;
$("#counter").html(curlen);
});
});
$("#counter").text($("#myTextArea").val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="myTextArea"></textarea><br>
Size: <span id="counter" />

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");
count = document.querySelector("label");
ta.addEventListener("input", function (e) {
count.innerHTML = this.value.length;
});
<textarea id="my-textarea" rows="4" cols="50" maxlength="10">
</textarea>
<label for="my-textarea"></label>

var maxchar = 10;
$('#message').after('<span id="count" class="counter"></span>');
$('#count').html(maxchar+' of '+maxchar);
$('#message').attr('maxlength', maxchar);
$('#message').parent().addClass('wrap-text');
$('#message').on("keydown", function(e){
var len = $('#message').val().length;
if (len >= maxchar && e.keyCode != 8)
e.preventDefault();
else if(len <= maxchar && e.keyCode == 8){
if(len <= maxchar && len != 0)
$('#count').html(maxchar+' of '+(maxchar - len +1));
else if(len == 0)
$('#count').html(maxchar+' of '+(maxchar - len));
}else
$('#count').html(maxchar+' of '+(maxchar - len-1));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="message" name="text"></textarea>

$(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');
}
});
});

This solution will respond to keyboard and mouse events, and apply to initial text.
$(document).ready(function () {
$('textarea').bind('input propertychange', function () {
atualizaTextoContador($(this));
});
$('textarea').each(function () {
atualizaTextoContador($(this));
});
});
function atualizaTextoContador(textarea) {
var spanContador = textarea.next('span.contador');
var maxlength = textarea.attr('maxlength');
if (!spanContador || !maxlength)
return;
var numCaracteres = textarea.val().length;
spanContador.html(numCaracteres + ' / ' + maxlength);
}
span.contador {
display: block;
margin-top: -20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea maxlength="100" rows="4">initial text</textarea>
<span class="contador"></span>

Related

dynamically count textarea symbols in a simple input

Good day everyone
I have a simple textarea on a page,and I need to dynamically count number of symbols, show how much is left under the form,and limit number of characters should be 350.
Thanks in advance.
What i exactly need is to display how many symbols are left to type
function limit(element)
{
var max_chars = 350;
if(element.value.length > max_chars) {
element.value = element.value.substr(0, max_chars);
}
}
<textarea onkeydown="limit(this);" onkeyup="limit(this);"></textarea>
var max_chars = 5;
var charsLeftDisplay = document.getElementById("charsLeft");
function limit(element) {
if (element.value.length > max_chars) {
element.value = element.value.slice(0, -1);
return false;
}
charsLeftDisplay.innerHTML = (max_chars - element.value.length) + " characters left...";
}
<textarea onkeyup="limit(this)"></textarea>
<p id="charsLeft"></p>
I think the best way to do this would be to use JQuery
here's the html
<textarea id="textareaID" rows="4" cols="50" maxlength="50"></textarea>
<p id="numberOfChars"><strong>Character typed:</strong> 0</p>
<p><strong>Max Character:</strong> 50</p>
and here's the jquery code
$('#textareaID').bind('input propertychange', function() {
if(this.value.length){
$("#numberOfChars").html("<strong>Character typed:</strong> "+this.value.length);
}
});
and here's a working fiddle as well https://jsfiddle.net/Visrozar/zbw7j64j/
Here is a simple solution,
just display the leftCharacters in a placeholder;
<script>
$(function() {
var $textarea = $('textarea');
var $input = $('input[name="spaces"]');
var maxLength = $textarea.attr('maxlength');
$input.val(maxLength);
$textarea.on('input', function() {
var currentLength = $textarea.val().length;
var leftCharacters = (maxLength - currentLength);
$input.val(leftCharacters);
});
});
</script>
<textarea name=test" maxlength="350"></textarea>
<input name="spaces" disabled />
This solution really works very well:
1 - Insert a div with id="textarea_count" for example in the place you want to show remaining characters, in your HTML file, near your textarea element (above or under):
<div class="form-group">
<label asp-for="DescCompetencia" class="col-md-2 control-label"></label>
<div class="col-md-10">
<textarea asp-for="DescCompetencia" class="form-control" rows="5"></textarea>
<span asp-validation-for="DescCompetencia" class="text-danger"></span>
<div id="textarea_count"></div>
</div>
</div>
2 - Insert in your javascript file or after /html element in the page you are editing the textarea element:
$(document).ready(function () {
var text_max = 500; //change by your max desired characters
var text_min = 7; //change to your min desired characters (or to zero, if field can be blank))
if ($('#DescCompetencia').length) {
var texto_disponivel = text_max - $('#DescCompetencia').val().length;
}
$('#textarea_count').html(texto_disponivel + ' caracteres disponíveis para digitar');
$('#DescCompetencia').keyup(function () {
var text_length = $('#DescCompetencia').val().length;
var text_remaining = text_max - text_length;
if (text_length <= text_min) {
$('#textarea_count').html(text_remaining + ' caracteres remanescentes. Digite ' + text_min + ' ou mais caracteres.');
}
else {
$('#textarea_count').html(text_remaining + ' caracteres remanescentes');
}
}); });
Must have Jquery already loaded before calling the above function.

A character counter in js?

So I am currently programming my very first website. I am using pure javascript. A part of it will be a comments section - which are stored in a SQL- Database on the server. I want comments to have a maximum length. After searching the web I found this solution. Please do note that this solution is far from perfect.
var maxchar = 160;
var i = document.getElementById("textinput");
var c = document.getElementById("count");
c.innerHTML = maxchar;
i.addEventListener("keydown", count);
function count(e) {
var len = i.value.length;
if (len >= maxchar) {
e.preventDefault();
} else {
c.innerHTML = maxchar - len - 1;
}
}
textarea {
display: block;
width: 200px;
height: 100px;
}
Remaining characters: <span id="count"></span>
<textarea id="textinput">
</textarea>
I found a lot of similar solutions also using jQuery. Now this solution has two major flaws. First it counts the characters before the new character is entered since the registered event is the keydown event - value.length will always give the old count. Secondly once you hit the maximum amount of characters it will prevent all user input - there is no way to delete characters anymore.
Registering the count to keyup doesn't help either - it can't prevent the input of the keydown event.
What is a better solution than this?
So after playing around with it for a bit I came up with this solution. The trick is to split up the count function into two parts - one which counts the characters and one which prevents the user input. Register the preventInput() on keydown, such that the input is prevented before entering, and register the count() on keyup, such that the new value of length is used in the function.
function preventInput(event) {
if (event.target.id == 'commentText')
var maxchar = 255;
else
var maxchar = 20;
//I'm using target here, such that I can use this as a callback for different textfields
var len = event.target.value.length;
var key = event.keyCode || event.which;
//prevent every input apart from UP, DOWN, LEFT, RIGHT and BACKSPACE
if (len >= maxchar && (key != 8 && !(key >= 37 && key <= 40)))
event.preventDefault();
}
function count(event) {
//different lengths for different textfields
if (event.target.id == 'commentText')
var maxchar = 255;
else
var maxchar = 20;
var len = event.target.value.length;
//setting the remaining chars field depending whether Author or Text triggered the event
document.getElementById("remain" + event.target.id.split('comment')[1]).innerHTML = 'Remaining characters:' + (maxchar - len);
//disable the submit button when the user entered too many chars (CTRL + V)
var btn = document.getElementById("submitBtn");
if (len > maxchar)
btn.disabled = true;
else
btn.disabled = false;
}
function setup() {
//setting to events
document.getElementById("commentAuthor").addEventListener("keydown", preventInput);
document.getElementById("commentAuthor").addEventListener("keyup", count);
document.getElementById("commentText").addEventListener("keydown", preventInput);
document.getElementById("commentText").addEventListener("keyup", count);
//initial count
document.getElementById("remainAuthor").innerHTML += 20;
document.getElementById("remainText").innerHTML += 255;
}
.charCounter {
opacity: 0.4;
}
<body onload="setup()">
<form>
<fieldset style="display: inline-block;">
<legend>Submit a comment</legend>
Name:
<input type="text" id="commentAuthor" name="Name:">
<div class="charCounter" id="remainAuthor">Remaining characters:</div>
<textarea name="comment" id="commentText" rows="4" cols="100"></textarea>
<div class="charCounter" id="remainText">Remaining characters:</div>
<br>
<input type="submit" id="submitBtn" value="Submit Comment!">
</fieldset>
</form>
</body>
You can modify the first snipped into something like this
var maxchar = 160;
var i = document.getElementById("commentText");
var c = document.getElementById("remainText");
c.innerHTML = maxchar;
i.addEventListener("keydown", count);
function count(e) {
var len = i.value.length;
len >= maxchar ? i.value = i.value.slice(0,len-1) : c.innerHTML = maxchar - len - 1;
}
<body onload="setup()">
<form>
<fieldset style="display: inline-block;">
<legend>Submit a comment</legend>
Name:
<input type="text" id="commentAuthor" name="Name:">
<div class="charCounter" id="remainAuthor">Remaining characters:</div>
<textarea name="comment" id="commentText" rows="4" cols="100"></textarea>
<div class="charCounter" id="remainText">Remaining characters:</div>
<br>
<input type="submit" id="submitBtn" value="Submit Comment!">
</fieldset>
</form>
</body>

Disallow special characters in textbox validation

I have javascript code where the validation does not allow more than 20 characters in text box. But, I also want to disallow in special characters in the validation; how can this be accomplished.
Here is my current validation code:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.2.js">
/script>
<script type='text/javascript'>
$(function()
{ $('#QI4562040').keyup(function()
{
var desc = $('#QI4562040').val();
var len = desc.length;
if (desc.length >= 10)
{
this.value = this.value.substring(0, 10);
} $('#spntxt').text(10 - len + ' Characters Left');
});
}); </script>
try bellow script this will not allow special charter # $ % ^ & * ( )
function validate() {
var element = document.getElementById('input-field');
element.value = element.value.replace(/[^a-zA-Z0-9#]+/, '');
};
<input type="text" id="input-field" onkeyup="validate();"/>
I just use your codes and modify:
$(function()
{ $('#QI4562040').keyup(function()
{
var desc = $('#QI4562040').val();
var lastChar = desc.slice(-1);
var spc = !((lastChar.charCodeAt()>=48&&lastChar.charCodeAt()<=57)||(lastChar.charCodeAt()>=65&&lastChar.charCodeAt()<=90)||(lastChar.charCodeAt()>=97&&lastChar.charCodeAt()<=122));
if (desc.length >= 10 || spc)
{
this.value = this.value.substring(0, desc.length-1);
} $('#spntxt').text(10 - len + ' Characters Left');
});
});
You must use the keypress event
<input type="text" onkeypress="return isValidCharacter(event)" />
and define the javascript event, the validation can do it with regular expressions
function isValidCharacter(e) {
var key;
document.all ? key = e.keyCode : key = e.which;
var pressedCharacter = String.fromCharCode(e)
var regExp = /^[a-zA-ZÁÉÍÓÚáéñíóú ]*$/;
return regExp.test(pressedCharacter); }
If the method returns true the character will be printed
For Input Length, use Html5 Max Length Property
$(function(){
$('#QI4562040').keyup(function(){
var input_val = $(this).val();
var inputRGEX = /^[a-zA-Z0-9]*$/;
var inputResult = inputRGEX.test(input_val);
if(!(inputResult))
{
this.value = this.value.replace(/[^a-z0-9\s]/gi, '');
}
$('#spntxt').text(10 - input_val.length + ' Characters Left');
});
});
<input type='text' name='' id='QI4562040' maxlength='10'/>
<div id='spntxt'></div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>

JQuery show / hide button dependents on number of textarea characters

function countChar(val) {
var len = val.value.length;
if (len == 0 || len == null) {
$('#sending').hide();
} else if (len >= 500) {
val.value = val.value.substring(0, 500);
} else {
$('#char_no').text(len + " / 500");
}
};
<textarea id="txt" rows="10" cols="40" onkeyup="countChar(this)"></textarea>
<div id="char_no">0 / 500</div>
<input id="sending" type="submit" value="POST">
Above is my JavaScript and html, it can calculate how many characters are contained in textArea, but I want to hide the submit button if user didn't input anything, or user inputed something but erased them all. any ideas?
You can use toggle to show or hide the button. Also it is recommended to add the event in JavaScript, instead of the markup.
function countChar() {
if (this.value.length > 500) {
this.value = this.value.substring(0, 500);
}
var len = this.value.length;
$('#sending').toggle(!!len); // !! casts a boolean
$('#char_no').text(len + " / 500");
};
$('#txt').on('input', countChar);
Note that this inside the function refers to the element.
DEMO: http://jsfiddle.net/19sLaw7w/1/
<!-- HTML -->
<textarea id = "myinput"></textarea>
<button style = "display: none" id = "mybutton">Submit</button>
Events are neat:
// Pure JS
var myinput = document.getElementById('myinput');
var mybutton = document.getElementById('mybutton');
myinput.onchange = function()
{
var charcount = myinput.value.length;
if(charcount == 0)
{
mybutton.style.display = 'none';
}else{
mybutton.style.display = 'inherit';
}
}
// jQuery
$('#myinput').on('change', function(){
var charcount = $(this).val().length;
if(charcount == 0)
{
$('#mybutton').hide();
}else{
$('#mybutton').show();
}
});

Limit number of lines in textarea and Display line count using jQuery

Using jQuery I would like to:
Limit the number of lines a user can enter in a textarea to a set number
Have a line counter appear that updates number of lines as lines are entered
Return key or \n would count as line
$(document).ready(function(){
$('#countMe').keydown(function(event) {
// If number of lines is > X (specified by me) return false
// Count number of lines/update as user enters them turn red if over limit.
});
});
<form class="lineCount">
<textarea id="countMe" cols="30" rows="5"></textarea><br>
<input type="submit" value="Test Me">
</form>
<div class="theCount">Lines used = X (updates as lines entered)<div>
For this example lets say limit the number of lines allowed to 10.
html:
<textarea id="countMe" cols="30" rows="5"></textarea>
<div class="theCount">Lines used: <span id="linesUsed">0</span><div>
js:
$(document).ready(function(){
var lines = 10;
var linesUsed = $('#linesUsed');
$('#countMe').keydown(function(e) {
newLines = $(this).val().split("\n").length;
linesUsed.text(newLines);
if(e.keyCode == 13 && newLines >= lines) {
linesUsed.css('color', 'red');
return false;
}
else {
linesUsed.css('color', '');
}
});
});
fiddle:
http://jsfiddle.net/XNCkH/17/
Here is little improved code. In previous example you could paste text with more lines that you want.
HTML
<textarea data-max="10"></textarea>
<div class="theCount">Lines used: <span id="linesUsed">0</span></div>
JS
jQuery('document').on('keyup change', 'textarea', function(e){
var maxLines = jQuery(this).attr('data-max');
newLines = $(this).val().split("\n").length;
console.log($(this).val().split("\n"));
if(newLines >= maxLines) {
lines = $(this).val().split("\n").slice(0, maxLines);
var newValue = lines.join("\n");
$(this).val(newValue);
$("#linesUsed").html(newLines);
return false;
}
});
For React functional component that sets new value into state and forwards it also to props:
const { onTextChanged, numberOfLines, maxLength } = props;
const textAreaOnChange = useCallback((newValue) => {
let text = newValue;
if (maxLength && text.length > maxLength) return
if (numberOfLines) text = text.split('\n').slice(0, numberOfLines ?? undefined)
setTextAreaValue(text); onTextChanged(text)
}, [numberOfLines, maxLength])
A much ugly , but somehow working example
specify rows of textarea
<textarea rows="3"></textarea>
and then
in js
$("textarea").on('keydown keypress keyup',function(e){
if(e.keyCode == 8 || e.keyCode == 46){
return true;
}
var maxRowCount = $(this).attr("rows") || 2;
var lineCount = $(this).val().split('\n').length;
if(e.keyCode == 13){
if(lineCount == maxRowCount){
return false;
}
}
var jsElement = $(this)[0];
if(jsElement.clientHeight < jsElement.scrollHeight){
var text = $(this).val();
text= text.slice(0, -1);
$(this).val(text);
return false;
}
});
For the React fans out there, and possibly inspiration for a vanilla JS event handler:
onChange={({ target: { value } }) => {
const returnChar = /\n/gi
const a = value.match(returnChar)
const b = title.match(returnChar)
if (value.length > 80 || (a && b && a.length > 1 && b.length === 1)) return
dispatch(setState('title', value))
}}
This example limits a textarea to 2 lines or 80 characters total.
It prevents updating the state with a new value, preventing React from adding that value to the textarea.

Categories

Resources