Small modification to the limit of a textarea characters counter - javascript

The code below counts the chars typed in a textarea. If you reach the 250 limit you can not add more. How can I let people to type more than 250?
Like ok, you have 250 minimum but it doesn't mind if you put more than this. Thanks!
<script type='text/javascript'>
var maxLength=250;
function charLimit(el) {
if (el.value.length > maxLength) return false;
return true;
}
function characterCount(el) {
var charCount = document.getElementById('charCount');
if (el.value.length > maxLength) el.value = el.value.substring(0,maxLength);
if (charCount) charCount.innerHTML = maxLength - el.value.length;
return true;
}
</script>
<form>
<textarea onKeyPress="return charLimit(this)" onKeyUp="return characterCount(this)" rows="8" cols="40"></textarea>
</form>
<p><strong><span id="charCount">250</span></strong> more characters available.</p>

To allow the number of characters entered to exceed the maxLength, the following blocks of code should be removed.
function charLimit(el) {
if (el.value.length > maxLength) return false;
return true;
}
and
if (el.value.length > maxLength) el.value = el.value.substring(0,maxLength);
and
onKeyPress="return charLimit(this)"
You might also want to consider modifying the following line to prevent displaying negative numbers.
if (charCount) charCount.innerHTML = Math.max(maxLength - el.value.length, 0);

change this line:
var maxLength=250;
change it to whatever max you want

the maxLength is beeing restricted by a var named "maxLength"
If you change that value you can change the max value required, because of all that comprobations that you're making

Related

How to validate texarea by max value using Javascript

I need to validate text area as following code,
my code as follows, here I need set maximum length as 10 and, if user trying to enter more than 10 need to prevent and if it is backspace or delete need to allow for deleting purpose. and also need to show remaining character count in a paragraph. But this code not working well. Its not preventing text input after 10.
<textarea id="txtxasa" class="message-content" onkeyup="Validate(event,this)"></textarea>
<p id="MsgContentRemainingLimit" class="message-character-limit">10 characters remaining</p>
function Validate(e,vald) {
var code;
var txtLength = vald.value.length;
var remainingContent = 10 - txtLength;
$('#MsgContentRemainingLimit').text(remainingContent);
console.log(vald.value.length)
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
if (txtLength >=10 && (code != 8 || code != 46))
return false;
}
Have you tried adding maxlength="10" to the textarea. I've done it and it works for me.
In Javascript you can try like this
let element = document.getElementById('input-name');
let countElem = document.getElementById('counter').innerHTML;
element.addEventListener('input', function() {
let inputvalue = this.value;
let maxLength = 10;
//disable the input if reached the limit
if (inputvalue.length > maxLength) {
console.log('maximum character limit reached');
this.disabled = true;
}
//count the numbers
let count = parseInt(countElem, 10);
document.getElementById('counter').innerHTML = count - inputvalue.length;
if (inputvalue.length > count) {
document.getElementById('counter').innerHTML = 0;
}
});
<p>
<input placeholder="First Name" id="input-name" name="input">
</p>
<p>remaining characters:</p><span id="counter" style="font-size:25px; font-weight:600;">10</span><br>
In Html5 you can also use the <input maxlength='10'> to limit characters only as a frontend validation. onkeyup in your code will not work if the user copy text and right click and paste them.

Character Counter for multiple text areas

I have a form that has 3 text areas, a copy button, and a reset button. I want to add all the characters to one sum, then display that sum next to the copy/reset button. There is a 500 character limit, and the counter should start at 49 characters. Should I just take all my textareas and "Funnel" them into a var, then count that var? I'm not sure how I should approach this. I've tried this technique
but it only works with one text area, not the sum of all. If the char count goes above 500, I'd like the text to turn red and say "you've gone over your character limit." I do not want to restrict or limit the text once its over 500. I'm a little fried trying to find a solution, and I'm an obvious html/javascript novice.
I do not need to worry about the carriage return issue in firefox/opera since everyone will be using IE11.
<h1>
Enter your notes into the text boxes below
</h1>
<p>
Please avoid using too many abbreviations so others can read your notes.
</p>
<form>
<script type="text/javascript"><!--
// input field descriptions
var desc = new Array();
desc['kcall'] = 'Reason for Call';
desc['pact'] = 'Actions Taken';
desc['mrec'] = 'Recommendations';
function CopyFields(){
var copytext = '';
for(var i = 0; i < arguments.length; i++){
copytext += desc[arguments[i]] + ': ' + document.getElementById (arguments[i]).value + '\n';
}
var tempstore = document.getElementById(arguments[0]).value;
document.getElementById(arguments[0]).value = copytext;
document.getElementById(arguments[0]).focus();
document.getElementById(arguments[0]).select();
document.execCommand('Copy');
document.getElementById(arguments[0]).value = tempstore;
document.getElementById("copytext").reset();
}
--></script>
<p> Reason For Call: </p> <textarea rows="5" cols="40" id="kcall"></textarea><br>
<p> Actions Taken: </p> <textarea rows="5" cols="40" id="pact"></textarea><br>
<p> Recommendations: </p> <textarea rows="5" cols="40" id="mrec"></textarea><br>
<br>
<button type="button" onclick="CopyFields('kcall', 'pact', 'mrec');">Copy Notes</button>
<input type="reset" value="Reset"/>
</form>
I think this question is a little more tricky that you think, and is not cause the complex of count the number of character inside of a textarea thats is actually pretty simple. in jquery:
$("textarea").each(function(index, item){
sum += $(this).val().length;
});
The problem begins whit the keyup event since and how you manage that event, in my follow example, I pretty much manage when the user press the key like in regular state but if you start holding a key then stoping and copy and paste really quick, the event get lost a little bit and recover after the second keyup. Any way here is my full example with count of character counter, change from red to black and black to red if you over pass the max characters and validation for submit or not the form
Fiddle:
https://jsfiddle.net/t535famp/
HTML
<textarea></textarea>
<textarea></textarea>
<textarea></textarea>
<button class="reset"></button>
You have use <span class="characters"></span> of <span class="max"></span>
<button class="submit">submit</button>
JS
$(function(){
var counter = 0; //you can initialize it with any number
var max = 400; //you can change this
var $characters = $(".characters");
var $max = $(".max");
var submit = true;
$characters.html(counter);
$(".max").html(max);
function count(event){
var characters = $(event.target).val().length;
$characters.html(counter);
//sum the textareas
var sum = 0;
$("textarea").each(function(index, item){
sum += $(this).val().length;
});
counter = sum;
if(counter > max) {
$characters.css({ color : "red" });
submit = false;
}else{
$characters.css({ color : "black" });
submit = true;
}
}
$(document).on("keyup","textarea",count);
$(document).on("click",".submit",function(){
if(submit)
alert("done");
else
alert("you have more characters than " + max);
});
})
Good luck my 2 cents
function textareaLength() {
var charCount = 0;
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (textarea) { charCount += textarea.value.length; });
return charCount;
}
That will return the count of all textareas on the page. Change the querySelector to be more specific if you only want to count specific textareas.
One option would be to add onchange events to your textareas which call a function like below:
<script>
function validate() {
if(textareaLength() >= 500) {
//limit reached
}
}
function textareaLength() {
var charCount = 0;
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (textarea) { charCount += textarea.value.length; });
return charCount;
}
</script>
<textarea onchange="validate()"></textarea>
<textarea onchange="validate()"></textarea>
<textarea onchange="validate()"></textarea>
Count
Here's a really simple function:
function TextLength() {
return Array.prototype.reduce.call(
document.querySelectorAll('textarea'),
function(b,a) { return b+a.value.length }, 0);
}
Or with ES6:
const TextLength = () => Array.from(document.querySelectorAll('textarea')).reduce((b,a) => b + a.value.length, 0)
To use this:
TextLength();
Change
Now add this:
Array.prototype.forEach.call(document.querySelectorAll('textarea'), function (e) { e.oninput = TextLength });
And again, ES6:
Array.from(document.querySelectorAll('textarea')).forEach(e => e.oninput = TextLength );
Since the button is in the same form as the textarea elements, you can get a reference to the form using the button's form property. You can also get all the text area elements in the form using querySelectorAll, then loop over them, adding up the characters in each.
The following just counts the total number of characters in the textarea elements:
<button type="button" onclick="count(this)">Copy Notes</button>
and the function:
function count(el) {
var tas = el.form.querySelectorAll('textarea');
var numChars = 0;
for (var i=0, iLen=tas.length; i<iLen, I++) {
numChars += tas[i].value.length;
}
return numChars;
}
If you can rely on ES5+ methods, then you can do:
function count(el) {
return Array.prototype.reduce.call(el.form.querySelectorAll('textarea'),
function(numChars, ta){return numChars += ta.value.length}, 0);
}
Note that by convention, functions starting with a capital letter are reserved for constructors, so CopyFields should be copyFields.
Here's a working example:
function count(el) {
return Array.prototype.reduce.call(el.form.querySelectorAll('textarea'),
function(numChars, ta){return numChars += ta.value.length}, 0);
}
<form>
<textarea name="ta0"></textarea>
<textarea name="ta1"></textarea>
<textarea name="ta2"></textarea><br>
<input type="text" name="numChars">
<button type="button" onclick="this.form.numChars.value = count(this)">count</button>
<input type="reset">
</form>
If you have more than one textarea (Multiple) and you want to display character count on each textarea, you may try below code, as its working me like a charm.
$(document).ready(function () {
$('textarea').on("load propertychange keyup input paste",
function () {
var cc = $(this).val().length;
var id=$(this,'textarea').attr('id');
$('#'+id).next('p').text('character Count: '+cc);
});
$('textarea').trigger('load');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<textarea id="one">hello</textarea>
<p></p>
<textarea id="two"></textarea>
<p></p>
<textarea id="three"></textarea>
<p></p>

How to restrict Textbox value with the max value on key events?

I have a text box i want to restrict that value for max value using key events
I try with the below code and its work fine
function validateRange(ele) {
if(ele.val() < 0 || ele.val() > 100){
console.log('false');
}else{
console.log('true');
}
}
$('.digit-validation').keyup(function(event){
validateRange($(this));
});
HTML:
<form:input type="text" path="depth" cssClass="number inplace-textbox digit-validation" data-min="0" size="10" />
I would like if(ele.val() < 0 || ele.val() > 100) is stop keypress.
Update: I am trying to do range of values validation.
I'd suggest that you try and use the HTML5 input type of number, with min and max attributes:
<input type="number" min="0" max="100" />
JS Fiddle demo.
This allows the user to enter a number directly (using the keyboard, or copy/paste), and allows for control of the increments using the step attribute (step="2", for example, will allow increments, or decrements, of 2 on every click of the spinner arrows).
If, however, you must use a non-number input:
Number.prototype.between = function (a, b, inclusive) {
var min = Math.min.apply(Math, [a,b]),
max = Math.max.apply(Math, [a,b]);
return inclusive ? this >= min && this <= max : this > min && this < max;
};
$('.digit-validation').keydown(function(event){
var v = parseFloat(this.value + String.fromCharCode(event.which));
return parseFloat(v).between(0,100,true);
});
JS Fiddle demo.
Why do you not use maxlength HTML attribute ?
<input type="text" maxlength="100" />
There is no need to use JS to achieve this.
For your validation, you need 2 things :
check if the user enters a number
check if the user enters something between 0 and 100
For the 1st one, since you use jQuery, you can use $.isNumeric().
For the 2nd one, you need to parse the value as integer thanks to parseInt().
That would give you :
http://jsfiddle.net/tLwYX/
function validateRange(ele) {
var val = ele.val();
if(!$.isNumeric(val) || parseInt(val,10) < 0 || parseInt(val,10) > 100){
$('#result').html('false');
}else{
$('#result').html('true');
}
}
$('.digit-validation').keyup(function(event){
validateRange($(this));
});

Comparing two input fields

I have this function which i am using to compare two input fields. If the user enters the same number in both the text field. On submit there will be an error. Now i would like to know if there is a way to allow same number but not higher than or lower the value of the previous text box by 1. For example if user enters 5 in previous text box, the user can only input either 4, 5 or 6 in the other input field.Please give me some suggestions.
<script type="text/javascript">
function Validate(objForm) {
var arrNames=new Array("text1", "text2");
var arrValues=new Array();
for (var i=0; i<arrNames.length; i++) {
var curValue = objForm.elements[arrNames[i]].value;
if (arrValues[curValue + 2]) {
alert("can't have duplicate!");
return false;
}
arrValues[curValue] = arrNames[i];
}
return true;
}
</script>
<form onsubmit="return Validate(this);">
<input type="text" name="text1" /><input type="text" name="text2" /><button type="submit">Submit</button>
</form>
A tidy way to do it which is easy to read:
var firstInput = document.getElementById("first").value;
var secondInput = document.getElementById("second").value;
if (firstInput === secondInput) {
// do something here if inputs are same
} else if (firstInput > secondInput) {
// do something if the first input is greater than the second
} else {
// do something if the first input is less than the second
}
This allows you to use the values again after comparison as variables (firstInput), (secondInput).
Here's a suggestion/hint
if (Math.abs(v1 - v2) <= 1) {
alert("can't have duplicate!");
return false;
}
And here's the jsfiddle link, if you want to see the answer
Give them both IDs.
Then use the
if(document.getElementById("first").value == document.getElementById("second").value){
//they are the same, do stuff for the same
}else if(document.getElementById("first").value >= document.getElementById("second").value
//first is more than second
}
and so on.

Text area white spaces in form

I have one form in with textarea:
<textarea wrap="physical" cols="28" rows="5" name="<portlet:namespace />tsSummary" onKeyDown="CountRight(this.form.<portlet:namespace />tsSummary,this.form.right,200);getElementById('char_count_summary').innerHTML = this.value.length" onKeyUp="CountRight(this.form.<portlet:namespace />tsSummary,this.form.right,200);getElementById('char_count_summary').innerHTML = this.value.length" onfocus="getElementById('char_count_summary').innerHTML = this.value.length">
<c:choose><c:when test="<%=Validator.isNotNull(dMang)%>"><%=dMang.getTsSummary()%></c:when><c:otherwise><%=""%></c:otherwise></c:choose>
</textarea>
<b><span id=char_count_summary></span></b>
<input readonly type="hidden" name="right" size=3 maxlength=3>
Javascript for limiting count to 200:
function CountRight(field, count, max) {
// if the length of the string in the input field is greater than the max value, trim it
if (field.value.length > max)
field.value = field.value.substring(0, max);
else
// calculate the remaining characters
count.value = max - field.value.length;
}
But, I get extra leading white spaces whenever i open the form and it takes extra characters showing count more than 200.
How can I remove extra blank spaces before content?
Remove the spaces in the source from between <textarea …> and <c:choose>
function trim(value) {
value = value.replace(/^\s+/,'');
value = value.replace(/\s+$/,'');
return value;
}
this removes any whitespace on the start or end of a string. You could do something like
field.value = trim(field.value);

Categories

Resources