A character counter in js? - javascript

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>

Related

For loop with user input javascript

So basically I have a for loop and I am trying to get it to run x amount of times. Depending on what the user inputs. The issue I am having is how to get the user input and also make sure that its a number not any other type of input. making them try again if its wrong.
It's simple really
Input Number : <input id="numberinput" onkeypress="return event.charCode >= 48 && event.charCode <= 57" />
<button id="btn" onclick="doAction()">
Send
</button>
<script>
var doAction = function () {
var input = document.getElementById('numberinput');
var times = parseint(input.value);
for(var i = 0; i < times; i++) {
//do whatever you need to do
}
}
</script>
In HTML5 you can use <input type="number"> to restrict an input to numeric characters only.
For older browsers, that are not HTML5-compatible, use <input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>. This utilizes Javascript to make sure that only numeric input is accepted into the input box.
Check out the snippet below for both solutions in action:
Javascript-based:<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>
<br><br>
HTML5 solution (preferred):<input type="number">
Fiddle
HTML
<input type="number" id="myInput">
<button id="myButton">Run Loop</button>
Javascript
$('body').on('click', '#myButton', function() {
var input = $('#myInput').val();
for(var i = 0; i < input; i++) {
alert('You have written inside input field: ' + input + ". This is Alert #" + (i+1))
}
});
To get the value from the input, you can use the value property of the input element.
To make sure the input is a number, you can specify type="number" if HTML5 is supported as mentioned in Angelos Chalaris's answer.
document.getElementById('btn').onclick = function(){
var totalIterations = parseInt(document.getElementById('input').value);
var output = document.getElementById('output');
output.innerHTML = '';
for(var i = 1; i <= totalIterations; i ++) {
var item = document.createElement('div');
item.innerHTML = i;
output.appendChild(item);
}
};
<input id="input" type="number"/>
<input id="btn" type="button" value="Do loop"/>
<div id="output"></div>
Here is an example using user input dialog:
var input, parsedInput = 0;
do {
input = prompt("Please enter valid number", "1");
parsedInput = parseInt(input);
} while(isNaN(parsedInput) || parsedInput < 0);
// keep trying on invalid input or negative number
for( i=0; i< parsedInput ; i++){
console.log("loop " + i);
}
HTML:
<input type="text" name="somefield" id="someid" value="10" />
JS:
var userInput = document.getElementById('someid').value;
if( Number.isInteger(parseInt(userInput)) )
{
// do something
}
Also, Number.isInteger() does not work on Internet explorer 11 or earlier.

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

JavaScript function runs for 1 second then clears?

So I've written a web page with a few JavaScript functions.
The page runs perfectly in Dreamweaver but when I tried it out in a browser (Google Chrome and Firefox) the JavaScript flashes for a split second then clears. I have no idea at all why this is.
<body>
<form name="myForm">
<ol>
<li>
<h1> TILE CALCULATOR</h1>
</li>
<li>
<label for="wall height">Wall height (cm)</label>
<input type="text" id="wall_height" />
</li>
<li>
<label for="wall width">Wall Width (cm)</label>
<input type="text" id="wall_width" />
</li>
<li>
<label for="tile height">Tile Height (cm)</label>
<input type="text" id="tile_height" />
</li>
<li>
<label for="tile width">Tile Width (cm)</label>
<input type="text" id="tile_width" />
</li>
<button onclick="javascript:validate();"> Calculate </button>
</ol>
</form>
<br />
<p id="result"></p>
<br />
<canvas id="myCanvas">
Your browser does not support this feature</canvas>
<br />
<br />
<script language="javascript" type="text/javascript">
//functoin to validate the inputs by the user
//user can only enter a number and all fields must be filled
function validate()
{
//first make sure canvas is clear
clearCanvas()
//take the inputs as variables
var x = document.getElementById("tile_width").value;
var y = document.getElementById("tile_height").value;
var z = document.getElementById("wall_width").value;
var i = document.getElementById("wall_height").value;
//check if the user has entered nothing and alert if they have
if (x==null || x=="" || y==null || y=="" || z==null || z=="" || i==null || i=="")
{
alert("All the fields have to be filled out!");
clearResult();
}
// check if the user has entered invalid values, only numbers can be entered
if (isNaN(x) == true || isNaN(y) == true || isNaN(z) == true || isNaN(i) == true)
{
alert("Dimensions can only be numbers!");
clearResult();
}
//check for negatives
if (x <= 0 || y <= 0 || z <= 0 || i <= 0)
{
alert("invalid dimension input, positive non-zero values only");
clearResult();
}
//if valid calculate tiles and print
else
tileCalculator();
}
function tileCalculator()
{
//take the input as variables
var tileWidth = document.getElementById("tile_width").value;
var tileHeight = document.getElementById("tile_height").value;
var wallWidth = document.getElementById("wall_width").value;
var wallHeight = document.getElementById("wall_height").value;
//find the areas of the tile and the wall
var tileArea = tileWidth * tileHeight;
var wallArea = wallWidth * wallHeight;
//divide these to find the number of tiles needed
var noOfTiles = (wallArea/tileArea);
//prints the result of noOfTiles
document.getElementById("result").innerHTML=" The number of Tiles you will need are : " + noOfTiles;
//scalled tiles to the canvas width of your choice
var scalledWidth = 500;
var ratioHW = wallHeight/wallWidth;
var scalledHeight = ratioHW*scalledWidth;
//scaled tile sizes
//scale the tiles to correct pixels
var scalledTileWidth = (tileWidth/wallWidth)*scalledWidth;
var scalledTileHeight = (tileHeight/wallHeight)*300;
//finds the number of tiles needs in a row
var noWidth = wallWidth/tileWidth;
//number of tiles in a column
var noHeight = wallHeight/tileHeight;
var canvas = document.getElementById("myCanvas");
canvas.style.width=scalledWidth + "px";
canvas.style.height=scalledHeight + "px";
printWall(0,0,noWidth,scalledTileWidth,(scalledTileHeight/2),noHeight);
}
//print a tile given the position and dimensions
function printTile(x,y,tileWidth,tileHeight)
{
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillRect(x,y,tileWidth,tileHeight);
}
//prints one row of tiles given the starting position and number to be printed
function printTileRow(x,y,numberOfTiles,tileWidth,tileHeight)
{
var start = 0;
//loops upto number of tiles in a row
while (start < numberOfTiles)
{
//prints a tile each time
printTile(x,y,tileWidth,tileHeight);
//next brick position
x = x + (tileWidth + 1); // add a space between tiles here.
start++;
}
}
//prints the wall
function printWall(x,y,numberOfTiles,tileWidth,tileHeight,numberOfRows)
{
//holds whether last row was shifted
var shiftCount = 0;
//starting index
var start = 0;
//loop up adding a row until required number of rows
while (start < numberOfRows)
{
//prints half a tile at the start of each row
printTile(0,y,(0.5 * tileWidth - 1),(tileHeight));
//prints the row
printTileRow((x+shiftCount),y,numberOfTiles,tileWidth,tileHeight);
//if shifted
if (shiftCount > 0)
{
//was shifted last row
shiftCount = 0;
}
else
{
//was not shifted last row
shiftCount = shiftCount + (0.5*tileWidth);
}
start++;
//start next row
y = y + (tileHeight + 1);
}
}
//clears the canvus each time the button is pressed
function clearCanvas()
{
//reset canvus to 300 by 300 and clear
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext('2d');
canvas.style.height="300px";
canvas.style.width="300px";
context.clearRect(0,0,300,300);
}
function clearResult()
{
document.getElementById("result").innerHTML="";
}
</script>
</body>
I would really appreciate it if someone could have a quick look for me! Thanks,
Try using onclick="javascript:validate();" on the form tag instead of on the button tag and try using 'onsubmit' instead of 'onclick'
Just replace your onclick attribute by onclick='validate(); return false'.
OR (better then previous)
Just add a type="button" attribute to your button tag, once the HTML5 button's default behavior is to submit forms.
Useful tip
Bind your handler programatically, this way (with no jQuery):
<button type="button" id="calculate"> Calculate </button>
...
window.addEventListener("load", function(){
document.getElementById("calculate").addEventListener("click", validate);
});
there is no problem with kepping the button in the form you you need to return false everytime to avoid the form submit using the return false like this
onclick="javascript:validate();return false;"

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>

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