How to show remaining characters if the textarea is prefilled? - javascript

If I have prefilled textarea, the 250 characters don't actually count the default words already in there. It only starts counting if you start typing something in it.
Also, how do I change the text color to yellow on "100 characters remaining" and change to red on "0 characters remaining"
Can someone help please?
function handle(){
let element = document.getElementById('input')
let value = element.value
let maxLength = element.maxLength
document.getElementById('remaining').innerText = `${maxLength - Number(value.length)} characters remaining`
}
<textarea col="8" rows="8" maxlength='250' onkeyup="handle()" id="input" value="">Hello World. Im born today.</textarea>
<p id='remaining'>250 characters remaining</p>

the 250 characters don't actually count the default words already in there. It only starts counting if you start typing something in it.
Just run your function once on page load:
function handle() {
let element = document.getElementById('input')
let value = element.value
let maxLength = element.maxLength
document.getElementById('remaining').innerText = `${maxLength - Number(value.length)} characters remaining`
}
handle();
<textarea col="8" rows="8" maxlength='250' onkeyup="handle()" id="input" value="">Hello World. Im born today.</textarea>
<p id='remaining'>250 characters remaining</p>
how do I change the text color to yellow on "100 characters remaining" and change to red on "0 characters remaining"
Do an if on each keyup:
function handle() {
let element = document.getElementById('input');
let value = element.value;
let maxLength = element.maxLength;
document.getElementById('remaining').innerText = `${maxLength - Number(value.length)} characters remaining`;
if (maxLength - Number(value.length) == 0) {
document.getElementById('remaining').style.color = "red";
} else if (maxLength - Number(value.length) <= 100) {
document.getElementById('remaining').style.color = "yellow";
}
}
handle();
<textarea col="8" rows="8" maxlength='250' onkeyup="handle()" id="input" value="">Hello World. Im born today.</textarea>
<p id='remaining'>250 characters remaining</p>

Related

String length as you are typing in javascript

I set the character validation for a password input to be 8. I want to input a function or an instruction (as the case may be) in javascript so that as I am typing the password, the background will be red if it isn't up to 8 characters yet and it would change to green if it has reached 8 characters and above
Try this :
function checkLength(textField) {
var strText = textField.value;
// if without spaces
strText = strText.replace(/^\s+|\s+$/g,"");
if(strText.length > 8) {
textField.style.backgroundColor = "#ff0000";
} else {
textField.style.backgroundColor = "#00FF00";
}
}
<input type="password" name="sometextfield" onkeyup="checkLength(this);" />

How do I limit a textarea box? [duplicate]

This question already has answers here:
Limit number of characters in input field
(10 answers)
textarea character limit
(10 answers)
Closed 3 years ago.
Can someone tell me how do I limit a text area to certain characters only? Let's say 250.
function handle(){
let element = document.getElementById('input')
let value = element.value
let maxLength = element.maxLength
document.getElementById('remaining').innerText = `${maxLength - Number(value.length)} characters remaining`
}
<textarea col="8" rows="8" maxlength='250' onkeyup="handle()" id="input" value="">Hello World. Im born today.</textarea>
<p id='remaining'>250 characters remaining</p>
You can use maxlength attribute of textarea
The maximum number of characters (unicode code points) that the user
can enter. If this value isn't specified, the user can enter an
unlimited number of characters.
<textarea col="8" rows="8" maxlength='5'></textarea>
And what if I want to show how many characters remaining? Like how I'm
seeing in the comments I'm writing?
function handle(){
let element = document.getElementById('input')
let value = element.value
let maxLength = element.maxLength
document.getElementById('remaining').innerText = `Remaining charcaters ${maxLength - Number(value.length)}`
}
<textarea col="8" rows="8" maxlength='250' onkeyup="handle()" id='input' value=''></textarea>
<p id='remaining'></p>

Adding a label to a text area which was created using javascript

If This question has been answered please direct me to the answer
I am working on creating a mobile application which is a form designed based off a form which is used at my job. Part of this form will require the input of numbers which must fall within a specific range of numbers. If the numbers input fall outside that range of numbers, the user will need to input "corrective actions" at the end of the form.
I have a javascript function to "validate" these input fields. I have also been able to get the same function to generate a <textarea> in the correct location, but when I try to get the function to pull the content of the input field's label and add it to the generated text area the function does not work.
The following is a small portion of both the HTML form and the javascript associated with the input fields:
<div id="coldtemp" data-role="ui-content">
<label for="bottomair">Maketable Air Temp (bottom)</label>
<input data-clear-btn="true" name="bottomair" required id="bottomair" type="number" size="3" onChange="coldValidate(this)">
<p class="tollorance"></p>
</div>
<div id="correction">
</div>
The javascript:
function coldValidate(elem) {
var lable = document.createElement("label");
var child = elem.parentNode.getElementByTagName("label").textContent;
//lable.appendChild(child);
var para = document.createElement("textarea");
var element = document.getElementById("correction");
var x, text;
x = +elem.value;
if (isNaN(x) || x < 33 || x > 40) {
text = "Temp Out of Tolerance</p>";
} else {
text = " ";
}
elem.parentNode.nextElementSibling.innerHTML = text;
//element.appendChild(lable);
element.appendChild(para);
}
I have tried variations on the .getElementBy javascript method but nothing works and I am truly stumped. I have also commented out part of the "label" code in an attempt to figure out what was going wrong, this is why the lable.appendChild(child); and element.appendChild(lable); are both commented out.
The problem is that you are using getElementByTagName("label"), which is invalid syntax. What you're looking for is getElementsByTagName("label")[0]:
function coldValidate(elem) {
var lable = document.createElement("label");
var child = elem.parentNode.getElementsByTagName("label")[0].textContent;
//lable.appendChild(child);
var para = document.createElement("textarea");
var element = document.getElementById("correction");
var x, text;
x = +elem.value;
if (isNaN(x) || x < 33 || x > 40) {
text = "Temp Out of Tolerance</p>";
} else {
text = " ";
}
elem.parentNode.nextElementSibling.innerHTML = text;
//element.appendChild(lable);
element.appendChild(para);
}
<div id="coldtemp" data-role="ui-content">
<label for="bottomair">Maketable Air Temp (bottom)</label>
<input data-clear-btn="true" name="bottomair" required id="bottomair" type="number" size="3" onChange="coldValidate(this)">
<p class="tollorance"></p>
</div>
<div id="correction">
</div>
Hope this helps! :)
EDIT:
The additional problem that you're facing with the commented code is due to you attempting to set child variable as the textContent of the label element, and then append it to the label. Instead, you need to set the child variable as the label itself, and append it to element, rather than lable:
function coldValidate(elem) {
var lable = document.createElement("label");
var child = elem.parentNode.getElementsByTagName("label")[0];
var para = document.createElement("textarea");
para.setAttribute("id", "textbox");
child.setAttribute("for", "textbox");
var element = document.getElementById("correction");
var x, text;
x = +elem.value;
if (isNaN(x) || x < 33 || x > 40) {
text = "Temp Out of Tolerance</p>";
} else {
text = " ";
}
elem.parentNode.nextElementSibling.innerHTML = text;
element.appendChild(child);
element.appendChild(para);
}
<div id="coldtemp" data-role="ui-content">
<label for="bottomair">Maketable Air Temp (bottom)</label>
<input data-clear-btn="true" name="bottomair" required id="bottomair" type="number" size="3" onChange="coldValidate(this)">
<p class="tollorance"></p>
</div>
<div id="correction">
</div>
Note that I have also given the new textbox an ID, and given the label a new 'for' field, which correlates to the new textbox.
Hope this helps! :)

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>

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