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

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.

Related

How to allow one specific word into text field in form using javascript?

I have input number field which is from 1000 to 10000 range but I also want to allow one only word 'All' into this field if user enter any word then show error. I have not written any JavaScript code for this because I do not have any idea how to do this. can anyone help me out please? Thanks
<input type="text" class="form-control" id="validationCustom02" min="1000" max="10000" required>
Here is my javascript solution: It uses a single If statement to check if the string is a number or ALL. Technically you don't need the isNaN function in there so if you want to remove it, the if statement will still work.
var _input = document.querySelector(".validate-num");
var _min= 1000;
var _max = 10000;
_input.addEventListener("input",function(){
var _valid = ((isNaN(this.value) && this.value.toLowerCase() == "all") || (!isNaN(this.value) && (this.value >= _min && this.value <= _max)));
if(!_valid){
var error = document.getElementById("error");
error.innerHTML = "Value Must be 1000 to 10000 or ALL";
}
});
<input type="text" class="validate-num form-control" id="validationCustom02" required>
A number type can't have strings into it, you will have to have a text input with an Event listener which does the validation job For You. Here, I have added a blur listener, it would trigger once you move away from the input.
const inputElem = document.querySelector('#validationCustom02required');
inputElem.addEventListener('blur', (e) => {
const val = e.target.value;
let showError = false;
if (isNaN(val)) {
if (val.toLowerCase() !== 'all') {
showError = true;
}
} else {
const numVal = +val;
if (val < 1000 || val > 10000) {
showError = true;
}
}
const errorElem = document.querySelector('#error');
if (showError) {
errorElem.innerText = 'Invalid; Value!';
} else {
errorElem.innerText = '';
}
})
<input type="text" class="form-control" id="validationCustom02required">
<div id="error"></div>

Jquery:Registration Number Validation on Keypress

I everyone I have a text-box
Number : <input type="text" name="Number" placeholder="MH03AH6414" id="txtRegNo" />
<span id="errmsg"></span>
The text-box must take value like the placeholder input(1st two character alphabet (a-z or A-Z) 2nd two character number (0-9) the 3rd two character alphabet (a-z or A-Z) and last four character number (0-9)
I have tried to do with key-press event and all but not formed properly
$("#txtRegNo").keypress(function (e) {
var dataarray = [];
var dInput = $(this).val();
for (var i = 0, charsLength = dInput.length; i < charsLength; i += 1) {
dataarray .push(dInput.substring(i, i + 1));
}
alert(dataarray);
alert(e.key);
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false
}
});
Please help me.
Thanks in advance
I tried of focusout which now works fine with me but I want to prevent from keyinput
Here is the jsfiddle solution
http://jsfiddle.net/ntywf/2470/
Try this out. Modified the function as per requirement
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
Number : <input type="text" name="Number" placeholder="MH03AH6414" id="txtRegNo" />
<span id="errmsg"></span>
<!-- end snippet -->
<script>
$("#txtRegNo").keyup(function (e) {
$("#errmsg").html('');
var validstr = '';
var dInput = $(this).val();
var numpattern = /^\d+$/;
var alphapattern = /^[a-zA-Z]+$/;
for (var i = 0; i < dInput.length;i++) {
if((i==2||i==3||i==6||i==7)){
if(numpattern.test(dInput[i])){
console.log('validnum'+dInput[i]);
validstr+= dInput[i];
}else{
$("#errmsg").html("Digits Only").show();
}
}
if((i==0||i==1||i==4||i==5)){
if(alphapattern.test(dInput[i])){
console.log('validword'+dInput[i]);
validstr+= dInput[i];
}else{
$("#errmsg").html("ALpahbets Only").show();
}
}
}
$(this).val(validstr);
return false;
});
</script>

Javascript Formatting Numbers With Commas and Dot

I want to create a javascript code to formatting my input number. For example when user type : 100000 it will convert automatically to 100,000 and if user type 1000.22 it will result 1,000.22. I have create code like this:
$(document).ready(function(){
$('input.angka').on("keyup click", function(event){
// skip for arrow keys
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var $this = $(this);
var num = $this.val().replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
// the following line has been simplified. Revision history contains original.
$this.val(num2);
});
});
function RemoveRougeChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" class="angka form-control" name="hargak" onkeyup="tots();" />
So all my input textbox which has class 'angka' will be converted. It works if I type it without decimals (10000, 20000, etc). But when I use decimal, these code gone wrong (1000.22 will result 1,000,.22) anyone can fix this code?
One possibility...
You should also accept navigating with arrows left and right...
$(document).ready(function(){
$('input.angka').on("keyup click", function(event){
// skip for arrow keys
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var $this = $(this);
var num = $this.val();
var decs = num.split(".");
num = decs[0];
num = num.replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRogueChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
if(decs.length > 1) {
num2 += '.' + decs[1];
}
$this.val(num2);
});
});
function RemoveRogueChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" class="angka form-control" name="hargak" onkeyup="tots();" />

HTML Input type number Thousand separator

I want to have a thousand separator (e.g. 1,000,000) in my Input field. However, it has to be of type number because I need to be able to adjust its value using "step". Code:
<input type="number" id='myNumber' value="40,000" step='100'>
I tried using Javascript to adjust the value but didn't work. Any help would be appreciated. Thanks!
Using autoNumeric plugin you can made a field as numeric input with different separators.
Include plugin:
<script src="~/Scripts/autoNumeric/autoNumeric.min.js" type="text/javascript"></script>
Html:
<input type="text" id="DEMO" data-a-sign="" data-a-dec="," data-a-sep="." class="form-control">
Script:
<script>
jQuery(function($) {
$('#DEMO').autoNumeric('init');
});
</script>
You can type only number, if you input 100000,99 you will see 100.000,99.
More: https://github.com/autoNumeric/autoNumeric
Check this webdesign.tutsplus.com tutorial
Final result is summarized here (look at direct Codepen playground)
$("#formInput".on("keyup", function(event ) {
// When user select text in the document, also abort.
var selection = window.getSelection().toString();
if (selection !== '') {
return;
}
// When the arrow keys are pressed, abort.
if ($.inArray(event.keyCode, [38, 40, 37, 39]) !== -1) {
return;
}
var $this = $(this);
// Get the value.
var input = $this.val();
input = input.replace(/[\D\s\._\-]+/g, "");
input = input?parseInt(input, 10):0;
$this.val(function () {
return (input === 0)?"":input.toLocaleString("en-US");
});
});
Notes:
toLocaleString() javascript function Actually show thousands separator (example and doc)
run below code in your console to get the idea
(30000000).toLocaleString('en-US',{useGrouping:true})
You can fake this functionality by using a pseudo-element to display the comma version.
div[comma-value]{
position:relative;
}
div[comma-value]:before{
content: attr(comma-value);
position:absolute;
left:0;
}
div[comma-value] input{
color:#fff;
}
A wrapping div is required because inputs can't have pseudo elements.
<div>
<input type="number" id='myNumber' value="40000" step='100'>
</div>
And a little bit of JavaScript to insert commas every third character
myNumber.value = commify(myNumber.value)
myNumber.addEventListener("change", function(){
commify(event.target.value)
})
function commify(value){
var chars = value.split("").reverse()
var withCommas = []
for(var i = 1; i <= chars.length; i++ ){
withCommas.push(chars[i-1])
if(i%3==0 && i != chars.length ){
withCommas.push(",")
}
}
var val = withCommas.reverse().join("")
myNumber.parentNode.setAttribute("comma-value",val)
}
Check out the fiddle
Create a mask input displaying the formatted number. This solution avoids changing the type or the value of the input.
$("input.mask").each((i,ele)=>{
let clone=$(ele).clone(false)
clone.attr("type","text")
let ele1=$(ele)
clone.val(Number(ele1.val()).toLocaleString("en"))
$(ele).after(clone)
$(ele).hide()
clone.mouseenter(()=>{
ele1.show()
clone.hide()
})
setInterval(()=>{
let newv=Number(ele1.val()).toLocaleString("en")
if(clone.val()!=newv){
clone.val(newv)
}
},10)
$(ele).mouseleave(()=>{
$(clone).show()
$(ele1).hide()
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="mask" type="number" value="12345.678"/>
csq recommends using the jQuery autoNumeric plugin. I found it to be very easy and intuitive to use.
My only gripe is that it forces <input type="text"> rather than <input type="number">. This means you lose the funcionality of step, but you gain users of your site being able to use commas in fields.
I guess you could use expected values of less than 1,000 as <input type="number"> and values more than 1,000 as <input type="text">
I've managed to pull it off after modifying https://stackoverflow.com/a/70726755/4829915 because:
The code didn't actually add commas due to not using Number().
It deleted the entire field when the initial value was blank.
No demo was provided.
Not saying the original approach was wrong or not, but I chose to use onfocus and onblur directly on the input itself.
Therefore, here's a revised answer:
Start with <input type="text">. You can still add min, max and step properties.
Add onfocus and onblur handlers to the <input> node:
function use_number(node) {
var empty_val = false;
const value = node.value;
if (node.value == '')
empty_val = true;
node.type = 'number';
if (!empty_val)
node.value = Number(value.replace(/,/g, '')); // or equivalent per locale
}
function use_text(node) {
var empty_val = false;
const value = Number(node.value);
if (node.value == '')
empty_val = true;
node.type = 'text';
if (!empty_val)
node.value = value.toLocaleString('en'); // or other formatting
}
<input type="text" min=0 onfocus="use_number(this)" onblur="use_text(this)">
function addCommas(nStr) { ....
In addition of yovanny's answer I create a Vue component which use this function.
Vue.component("in-n", {
template:
`<input #keyup="keyup" #keypress="isNumber($event)" v-model="text" type="text" />`,
props: ["value"],
data() {
return {
text: ""
}
},
methods: {
addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? ',' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
},
isNumber: function (evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 46) {
evt.preventDefault();;
} else {
return true;
}
},
keyup() {
this.text = this.addCommas(this.text.replace(/,/g, ''));
this.$emit("input", parseInt(this.text.replace(/,/g, '')))
}
}
})
I found a much simpler answer:
Start with <input type="text">. You can still add min, max and step properties.
Add onfocus and onblur handlers to the <input> node:
node.addEventListener('onfocus', () => {
const value = node.value;
node.type = 'number';
node.value = Number(value.replace(/,/g, '')); // or equivalent per locale
});
node.addEventListener('onblur', () => {
const value = node.value;
node.type = 'text';
node.value = value.toLocaleString(); // or other formatting
});
When the user selects the input, it will convert to a regular numeric input with thousands separators removed, but with a normal spinner. When the user blurs the input, it reverts to formatted text.
I add an onkeyup handler that blurs the input when the "enter" key is pressed.
I have updated #CollenZhou answer https://stackoverflow.com/a/67295023/6777672 as on mouse leave, input looses focus which is annoying. I have also added all input type numbers to selector as well as class.
$('input.thousands-separator, input[type="number"]').each((i,ele)=>{
let clone=$(ele).clone(false)
clone.attr('type','text')
let ele1=$(ele)
clone.val(Number(ele1.val()).toLocaleString('en'))
$(ele).after(clone)
$(ele).hide()
clone.mouseenter(()=>{
ele1.show()
clone.hide()
})
setInterval(()=>{
let newv=Number(ele1.val()).toLocaleString('en')
if(clone.val()!=newv){
clone.val(newv)
}
},10)
$(ele).mouseleave((event)=>{
if ($(ele).is(':focus')) {
event.preventDefault();
} else {
$(clone).show()
$(ele1).hide()
}
})
$(ele).focusout(()=>{
$(clone).show()
$(ele1).hide()
})
})
try
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? ',' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}

Count textarea characters

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>

Categories

Resources