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.
Related
I have this script to limit the words on a textarea but I want to use the same function to a form that contains multiple textarea tags.
What is the best way to reuse this and make an independent word counter and limiter for every textarea tag in the same form?
Thanks a lot in advance.
var wordLimit = 5;
var words = 0;
var jqContainer = $(".my-container");
var jqElt = $(".my-textarea");
function charLimit()
{
var words = 0;
var wordmatch = jqElt.val().match(/[^\s]+\s+/g);
words = wordmatch?wordmatch.length:0;
if (words > wordLimit) {
var trimmed = jqElt.val().split(/(?=[^\s]\s+)/, wordLimit).join("");
var lastChar = jqElt.val()[trimmed.length];
jqElt.val(trimmed + lastChar);
}
$('.word-count', jqContainer).text(words);
$('.words-left', jqContainer).text(Math.max(wordLimit-words, 0));
}
jqElt.on("keyup", charLimit);
charLimit();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="my-container">
<textarea class="my-textarea"></textarea>
<span class="words-left"></span> words left
<div>
You can use a generic function ($this) is the textarea element changed.
For relative elements, you can use the function .next(selector)
Also you can read parameters from attributes (maxwords for example).
var jqContainer = $(".my-container");
function charLimit()
{
var words = 0;
var jqElt=$(this);
var wordLimit = jqElt.attr("maxwords");
var words = 0;
var wordmatch = jqElt.val().match(/[^\s]+\s+/g);
words = wordmatch?wordmatch.length:0;
if (words > wordLimit) {
var trimmed = jqElt.val().split(/(?=[^\s]\s+)/, wordLimit).join("");
var lastChar = jqElt.val()[trimmed.length];
jqElt.val(trimmed + lastChar);
}
jqElt.next('.words-left').text(Math.max(wordLimit-words, 0));
}
$(".my-textarea", jqContainer).on("keyup", charLimit).keyup();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="my-container">
<textarea id="text1" class="my-textarea" maxwords="5"></textarea>
<span class="words-left"></span> words left
<textarea id="text1" class="my-textarea" maxwords="10"></textarea>
<span class="words-left"></span> words left
<div>
You can wrap your logic up in a function and reuse that function.
See example:
function wordCounter(container, limit) {
var wordLimit = limit;
var jqContainer = $(container);
var jqElt = $("textarea", jqContainer);
function charLimit()
{
var words = 0;
var wordmatch = jqElt.val().match(/[^\s]+\s+/g);
words = wordmatch?wordmatch.length:0;
if (words > wordLimit) {
var trimmed = jqElt.val().split(/(?=[^\s]\s+)/, wordLimit).join("");
var lastChar = jqElt.val()[trimmed.length];
jqElt.val(trimmed + lastChar);
}
$('.word-count', jqContainer).text(words);
$('.words-left', jqContainer).text(Math.max(wordLimit-words, 0));
}
jqElt.on("keyup", charLimit);
charLimit();
}
wordCounter(".my-container1", 5);
wordCounter(".my-container2", 10);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="my-container1">
<textarea class="my-textarea"></textarea>
<span class="words-left"></span> words left
</div>
<div class="my-container2">
<textarea class="my-textarea"></textarea>
<span class="words-left"></span> words left
</div>
Note that you had an issue in your example where the div tag wasn't closed.
if you need to use that same implementation you could add an id to each text area you are going to put in the form, then add an attribute for= to the corresponding spans pointing to the corresponding text area like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="my-container">
<textarea id="textarea-1" class="my-textarea" onkeyup="charLimit(this)"></textarea>
<span for="textarea-1" class="words-left"></span> words left
<textarea id="textarea-2" class="my-textarea" onkeyup="charLimit(this)"></textarea>
<span class="words-left" for="textarea-2"></span> words left
<div>
var wordLimit = 5;
var words = 0;
var jqContainer = $(".my-container");
function charLimit(elem)
{
var elm = $(elem)
var words = 0;
var wordmatch = elm.val().match(/[^\s]+\s+/g);
words = wordmatch?wordmatch.length:0;
if (words > wordLimit) {
var trimmed = elm.val().split(/(?=[^\s]\s+)/, wordLimit).join("");
var lastChar = elm.val()[trimmed.length];
elm.val(trimmed + lastChar);
}
$('.word-count', jqContainer).text(words);
$('[for='+ elm.attr('id') +']', jqContainer).text(Math.max(wordLimit-words, 0));
}
This is how I will normally do it:
Create a function that handles the word count refreshMaxWords()
Create a hook that can be tied up with the element <textarea data-max-words="5"></textarea>
(function($) {
var refreshMaxWords = function ($el) {
var wordLimit = parseInt($el.data('max-words')) || false,
wordmatch = $el.val().match(/[^\s]+\s+/g),
words = wordmatch ? wordmatch.length : 0,
// You can change how to get the "words-left" div here
$wordsLeft = $el.parent().find('.words-left');
if (wordLimit !== false) {
if (words > wordLimit) {
var trimmed = $el.val().split(/(?=[^\s]\s+)/, wordLimit).join("");
var lastChar = $el.val()[trimmed.length];
$el.val(trimmed + lastChar);
}
}
if ($wordsLeft.length > 0) {
$wordsLeft.html(Math.max(wordLimit - words, 0));
}
};
$(function () {
$(document).on('keyup.count-words', '[data-max-words]', function (e) {
refreshMaxWords($(this));
});
});
})(jQuery);
This is with assumption of HTML that looks like the following:
<div class="form-group">
<label>Input #1</label>
<textarea class="form-control" data-max-words="5"></textarea>
<p class="help-block"><span class="words-left">5</span> words left.</p>
</div>
<div class="form-group">
<label>Input #2</label>
<textarea class="form-control" data-max-words="10"></textarea>
<p class="help-block"><span class="words-left">10</span> words left.</p>
</div>
The benefits of this approach are:
Cleaner code structure
This can be reused on your other projects.
Notes:
You don't really need to wrap the javascript in
(function($) {
// your code here
})(jQuery);
I like doing it because it ensures that there won't be any conflict by accident.
I want to make java script function that makes new line when I press Enter key in input tag space.
Also I hope, when making new line, the height of input tag space dynamically stretches.
<!-- onkeydown function -->
function Enter(){
if(event.keyCode === 13){
var element = document.getElementById("PostingArea");
<!-- I don't know here -->
}
}
<!-- html code -->
<input class="PostingArea" id="PostingArea" onkeydown="Enter()">
You need to use textarea and indicate how many rows you expect, like this:
<textarea name="taText" cols="80" rows="25"></textarea>
Use textarea tag.using textarea multiple line text can be submitted.
Try this updated version
function onTestChange() {
var key = window.event.keyCode;
var el = document.getElementById("PostingArea");
var height = el.offsetHeight;
var newHeight = height + 20;
var value = el.val();
// If the user has pressed enter
if (key === 13) {
el.style.height = newHeight + 'px';
var newValue = value + '<br/>';
el.val(newValue)
return false;
}
if (event.keyCode == 8) {
el.style.height = newHeight - 'px';
var newValue = value - '<br/>';
el.val(newValue)
return false;
}
else {
return true;
}
}
<body>
<div id ="PostingArea" class="input-area" style="height:20px;" onkeypress="onTestChange()">
<input type="text" style="height:100%;" />
</div>
</body>
NEED HELP!
How to add one every time I click "Add" button?
The number will increase every time I click.
It's start from 0, after I click it's will plus 1 become 1, then 2 and etc.
HTML:
<div id="add_form">
<div class="form-field">
<div class="field">
<div class="no">0</div>
</div>
</div>
</div>
Add
<p><br /></p>
JQuery:
$(document).ready(function() {
var MaxInputs = 8;
var InputsWrapper = $("#add_form");
var AddButton = $("#add_field");
var x = InputsWrapper.length;
var FieldCount=1;
$(AddButton).click(function (e) {
if(x <= MaxInputs) {
FieldCount++;
$(InputsWrapper).append('<div class="field"><div class="no">1</div></div>');
x++;
}
return false;
});
});
My JQuery quite poor, need some help from you guys.
Also, here is the jsfiddle link.
http://jsfiddle.net/fzs77/
Really appreciate your help.
You have 1 hardcoded, so it can't change. Do it like this:
$(InputsWrapper).append('<div class="field"><div class="no">' + x + '</div></div>');
Check this JSFiddle with working demo.
You have to out the variable that holds the number inside of the html that you append. Also move the increscent of the FieldCount variable to below the append function call to render the correct result.
Like so:
$(AddButton).click(function (e) {
if(x <= MaxInputs) {
$(InputsWrapper).append('<div class="field"><div class="no">' + FieldCount + '</div></div>');
x++;
FieldCount++;
}
return false;
});
Try this jsfiddle:
http://jsfiddle.net/fzs77/7/
<div id="add_form">
<div class="form-field">
<div class="field">
<div class="no">0</div>
</div>
</div>
</div>
Add
<p><br /></p>
JS file
$(document).ready(function() {
var MaxInputs = 8;
var InputsWrapper = $("#add_form");
var AddButton = $("#add_field");
var x = InputsWrapper.length;
var FieldCount=0;
$(AddButton).click(function (e) {
if(x <= MaxInputs) {
FieldCount++;
$(InputsWrapper).append('<div class="field"><div class="no">' + FieldCount + '</div></div>');
}
return false;
});
});
Try this if you want to increment it while on the same line.
http://jsfiddle.net/sdMCH/
$(document).ready(function() {
$('#add_field').click(function (e) {
var x=$(".no");
x[0].innerHTML = (parseInt(x[0].innerHTML,10)+1);
}
);
});
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>
I am working on a project that requires me to count the number of characters entered in a text box and dynamically display the result elsewhere on the page.
As I said, this would preferably be done in jQuery or Javascript.
Thanks in advance.
You could do this in jQuery (since you said you preferred it), assuming you want the character count displayed in a div with id="characters":
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = $(this).val().length;
$('#characters').text(cs);
}
UPDATE: jsFiddle (by Dreami)
UPDATE 2: Updating to include keydown for long presses.
This is my preference:
<textarea></textarea>
<span id="characters" style="color:#999;">400</span> <span style="color:#999;">left</span>
Then jquery block
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = [400- $(this).val().length];
$('#characters').text(cs);
}
<script type="text/javascript">
function countChars(countfrom,displayto) {
var len = document.getElementById(countfrom).value.length;
document.getElementById(displayto).innerHTML = len;
}
</script>
<textarea id="data" cols="40" rows="5"
onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea><br>
<span id="charcount">0</span> characters entered.
Plain Javascript.
I would like to share my answer which i used in my project and it is working fine.
<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Rows="4" Columns="50" placeholder="Maximum limit: 100 characters"></asp:TextBox><br />
<span id="spnCharLeft"></span>
<script type='text/javascript'>
$('#spnCharLeft').css('display', 'none');
var maxLimit = 100;
$(document).ready(function () {
$('#<%= txtComments.ClientID %>').keyup(function () {
var lengthCount = this.value.length;
if (lengthCount > maxLimit) {
this.value = this.value.substring(0, maxLimit);
var charactersLeft = maxLimit - lengthCount + 1;
}
else {
var charactersLeft = maxLimit - lengthCount;
}
$('#spnCharLeft').css('display', 'block');
$('#spnCharLeft').text(charactersLeft + ' Characters left');
});
});
</script>
Source: URL
Though it has been already solved, I'm interested to share something that I have used in one of my projects:
<textarea id="message" cols="300" rows="200" onkeyup="countChar(this)"
placeholder="Type your message ..." >
</textarea>
<input id="text-character" class="input-mini uneditable-input"
placeholder="0 Chars" readonly />
<input id="text-parts" class="input-mini uneditable-input"
placeholder="0 Parts" readonly />
<input id="text-remaining" class="input-medium uneditable-input"
placeholder="160 Chars Remaining" readonly />
Javascript code:
function countChar(val) {
var len = val.value.length;
var ctext = len + " Chars";
var str = val.value;
var parts = [];
var partSize = 160;
while (str) {
if (str.length < partSize) {
var rtext = (partSize - str.length) + " Chars Remaining";
parts.push(str);
break;
}
else {
parts.push(str.substr(0, partSize));
str = str.substr(partSize);
}
}
var ptext = parts.length + " Parts";
$('#text-character').val(ctext);
$('#text-parts').val(ptext);
$('#text-remaining').val(rtext);
}
<script Language="JavaScript">
<!--
function Length_TextField_Validator()
{
var len = form_name.text_name.value.length; //the length
return (true);
}
-->
</script>
<form name="form_name" method="get" action="http://www.codeave.com/html/get.asp"
onsubmit="return Length_TextField_Validator()">
<input type="text" name="text_name">
<input type="submit" value="Submit">
</form>
Source(s) : Text Validation