...

View Full Version : Character Limiter



Scriptr
04-18-2012, 02:40 AM
A character limiter/counter that manages to do it all in just 28 lines of Javascript/JQuery and 2 pertinent lines of HTML


The JQuery/Javascript


$(document).ready(function(){
var hi = 200;
var cu = 0;
$("#rem").html(eval(hi - cu));
$("#in").keyup(function(){
var cu = $(this).val().length;
$("#rem").html(eval(hi - cu));
if(eval(hi - cu) < 0){
while(eval(hi - cu) < 0){
$(this).val( $(this).val().replace(/(\s+)?.$/, "") );
cu = cu - 1;
$("#rem").html(eval(hi - cu));
}
}
});
});


The HTML


<!DOCTYPE html>
<html>
<body>
<textarea id="in"></textarea><br>
<span>Characters Remaining: </span><span id="rem"></span>
</body>
</html>


Edit the var hi = 200; to change the character limit.

felgall
04-18-2012, 04:21 AM
You don't need jQuery or eval to do that in far less c ode than you have there.

Just another example of someone using jQuery to do something that can be done in fewer lines of ordinary JavaScript.

jmrker
04-18-2012, 05:11 PM
Six lines of a function with your two lines of HTML.
No jquery and no eval() usage.


<html>
<head>
<title> Untitled </title>
<script type="text/javascript">
// From: http://www.codingforums.com/showthread.php?t=257717

function ckTxtLen() {
var charLimit = 200;
var sel = document.getElementById('txtIn').value.length;
document.getElementById('txtRemain').innerHTML = charLimit-sel;
return true;
}
</script>

<style type="text/css">

</style>
</head>
<body>
<textarea id="txtIn" onkeypress="ckTxtLen()" maxlength="200"></textarea>
<div>Characters Remaining: <span id="txtRemain"></span></div>
</body>
</html>

You could also change a bit to make it so multiple <textarea>s could be used.
:)

Like this:


<html>
<head>
<title> Limit Textarea Input </title>
<script type="text/javascript">
// From: http://www.codingforums.com/showthread.php?t=257717

function ckTxtLen(IDS) {
var obj = document.getElementById(IDS);
document.getElementById(IDS+'Remain').innerHTML
= obj.getAttribute('maxlength') - obj.value.length;;
return true;
}
</script>

<style type="text/css">

</style>
</head>
<body>
<textarea id="txtIn0" onkeypress="ckTxtLen(this.id)" maxlength="200"></textarea>
<div>Chars. Remaining: <span id="txtIn0Remain">200</span></div>
<textarea id="txtIn1" onkeypress="ckTxtLen(this.id)" maxlength="100"></textarea>
<div>Chars. Remaining: <span id="txtIn1Remain">100</span></div>
<textarea id="txtIn2" onkeypress="ckTxtLen(this.id)" maxlength="50"></textarea>
<div>Chars. Remaining: <span id="txtIn2Remain">50</span></div>
</body>
</html>

:D

VIPStephan
04-19-2012, 01:52 AM
:D

You da man!



:D

Philip M
04-19-2012, 06:53 PM
Slight snag. The user can paste into the textarea, and if he pastes in 300 characters the remaining count shows -100.

Here is my proposal:-


<html>
<head>

<script type = "text/javascript">

var maxLen = 400; // max number of characters allowed // global variable
var max = "You may enter up to " + maxLen + " characters"; // global variable

function OnPaste () {
//return false; // cancels (blocks) the onpaste event. Uncomment this line to block pasting
setTimeout(checkMaxInput,100); // delay is necessary
}

function initCount() {
document.getElementById("limit").innerHTML = max;
document.getElementById("remLen").value = maxLen;
}

function checkMaxInput() {
var form = document.myform; // or document.forms[0] or document.getElementById("myform");
if (form.txtarea.value.length > maxLen) { // if too long.... trim it!
form.txtarea.value = form.txtarea.value.substring(0, maxLen);
document.getElementById("message").innerHTML = "Too many characters were entered!! The excess over " + maxLen + " have been removed.";
}
else {
document.getElementById("message").innerHTML = "";
}
form.remLen.value = maxLen - form.txtarea.value.length;
}

</script>

</head>

<body onload = "initCount()">

<form name = "myform" id = "myform">
<span id = "limit" style="font-size: 10pt;color: #FF0000;font-family: arial, helvetica, sans-serif;"></span>
<br>
<textarea name="txtarea" wrap=physical cols=48 rows=10 onkeyup="checkMaxInput()" onblur="checkMaxInput()" onpaste="OnPaste ()" >
</textarea>
<br>
<input readonly type=text name=remLen id = "remLen" size=3 value = ""> characters left</font>
</form>
<span id = "message" style="color:red";></span>
</body>
</html>

rnd me
04-19-2012, 10:31 PM
A character limiter/counter that manages to do it all in just 0 lines of Javascript/JQuery and 1 pertinent line of HTML:


<textarea maxlength="50"></textarea>

felgall
04-19-2012, 11:05 PM
A character limiter/counter that manages to do it all in just 0 lines of Javascript/JQuery and 1 pertinent line of HTML:


<textarea maxlength="50"></textarea>

maxlength is only valid on input fields - you can't use it on textarea fields as there is no such attribute on that field type.

The only way to limit textarea content client side is using JavaScript.

A version of this that I wrote many years ago can be found at http://www.felgall.com/jstip20.htm - that doesn't display the number of characters remaining though - athough adding it would only require one extra statement.

rnd me
04-21-2012, 09:53 PM
maxlength is only valid on input fields - you can't use it on textarea fields as there is no such attribute on that field type.


worked for me when i tried it. the textarea objects i looked at even have a "maxLength" dom binding... If nothing else, it's a good way to take care of a lot of visitors without js. It's also perfect to hold the length setting next to the other validation settings of the textarea like @required and @pattern, unlike Philip M's example when the validation restriction is not simply determinable by using "inspect element" on the textarea, and requires global variables that limit the checker's re-use.

see http://www.w3schools.com/html5/att_textarea_maxlength.asp for specifics.

edit:
i see it does not work in ie9, but does on 10.

felgall
04-22-2012, 12:34 AM
worked for me when i tried it. the textarea objects i looked at even have a "maxLength" dom binding... If nothing else, it's a good way to take care of a lot of visitors without js. It's also perfect to hold the length setting next to the other validation settings of the textarea like @required and @pattern,

So it must be one of the useful attributes that HTML 5 is adding - like pattern is a useful addition and unlike required which is not a useful addition because the addition of pattern makes required completely unnecessary.

Hashim1
04-28-2012, 09:55 PM
So, basically, the conclusion of this thread is that JS, or any script for that matter, is not needed to limit the amount of characters a user can enter in a text field, because it can be accomplished with a single HTML attribute? Is this correct? Or am I getting the wrong end of the stick?

felgall
04-28-2012, 11:34 PM
So, basically, the conclusion of this thread is that JS, or any script for that matter, is not needed to limit the amount of characters a user can enter in a text field, because it can be accomplished with a single HTML attribute? Is this correct? Or am I getting the wrong end of the stick?

It appears that the necessary attribute has been added to the textarea tag in HTML 5 so you'd only need to use JavaScript for browsers that haven't implemented that useful proposal yet. The attribute has always been available on input tags.

Hashim1
04-29-2012, 12:53 AM
It appears that the necessary attribute has been added to the textarea tag in HTML 5 so you'd only need to use JavaScript for browsers that haven't implemented that useful proposal yet. The attribute has always been available on input tags.

Is there anyway of finding which have and which haven't?

felgall
04-29-2012, 12:57 AM
Is there anyway of finding which have and which haven't?

Not really since browsers only implement it to allow testing at the moment as HTML 5 is still only a proposal.

If you add the attribute in the HTML then you could add a couple of lines of JavaScript that grab the attribute and perform the check using that value and then it wouldn't make any difference whether the browser supports the attribute directly or not.

possibly the following (since maxlength generally just discards what doesn't fit there would be no need for an error message):


<textarea rows="5" cols="50" maxlength="500"
onkeyup="if (this.value.length > this.maxlength) this.value = this.value.substring(0, this.maxlength)">

devnull69
04-29-2012, 09:41 AM
The limit can be accomplished by using the maxlength attribute only. But if you want to count the remaining characters you'll need to do some scripting.

Philip M
04-29-2012, 11:27 AM
So, basically, the conclusion of this thread is that JS, or any script for that matter, is not needed to limit the amount of characters a user can enter in a text field, because it can be accomplished with a single HTML attribute? Is this correct? Or am I getting the wrong end of the stick

Textbox - yes
Textarea - no (in HTML4)

Philip M
05-01-2012, 08:56 PM
Please note a correction to the script in Post #5:-

if (form.txtarea.value.length >= maxLen) { // if too long.... trim it!

Required to show the message if pasting is done with CTL-V

WolfShade
05-01-2012, 10:18 PM
function textCounter(field,countfield,maxlimit) {
if (field.value.length > maxlimit) {
field.value = field.value.substring(0, maxlimit);
}
else {
countfield.value = maxlimit - field.value.length;
}
}



<body onLoad="textCounter(document.forms['thisForm'].thisMessage,document.forms['thisForm'].remLen,1000);">
<form id="thisForm">
There are <input type="text" id="remLen" style="border:0px;" /> characters remaining<br />
<textarea id="thisMessage" cols=50 rows=6
onKeyUp="textCounter(this,document.forms['thisForm'].remLen,1000);"
onKeyDown="textCounter(this,document.forms['thisForm'].remLen,1000);"
onKeyPress="textCounter(this,document.forms['thisForm'].remLen,1000);"
onPaste="textCounter(this,document.forms['thisForm'].remLen,1000);"></textarea>
</form>
</body>

Just my $0.02 worth.

^_^

felgall
05-01-2012, 11:32 PM
function textCounter(field,countfield,maxlimit) {
if (field.value.length > maxlimit) {
field.value = field.value.substring(0, maxlimit);
}
else {
countfield.value = maxlimit - field.value.length;
}
}



<body onLoad="textCounter(document.forms['thisForm'].thisMessage,document.forms['thisForm'].remLen,1000);">
<form id="thisForm">
There are <input type="text" id="remLen" style="border:0px;" /> characters remaining<br />
<textarea id="thisMessage" cols=50 rows=6
onKeyUp="textCounter(this,document.forms['thisForm'].remLen,1000);"
onKeyDown="textCounter(this,document.forms['thisForm'].remLen,1000);"
onKeyPress="textCounter(this,document.forms['thisForm'].remLen,1000);"
onPaste="textCounter(this,document.forms['thisForm'].remLen,1000);"></textarea>
</form>
</body>

Just my $0.02 worth.

^_^

That code might have been appropriate for 1996 but was completely the wrong way to write JavaScript by 2004.

It wouldn't have even been all that good for 1996 since the keydown code is completely unnecessary since keypress picks up every character that is typed - any keydowns that don't also trigger a keypress are not adding any characters to the field. Also keypress and keyup are just processing the same code one extra time for each key pressed. Running the same code three times isn't going to give different answers than runnng it once.

ANY OF THE PRIOR VERSIONS POSTED IS AT LEAST A 1000% IMPROVEMENT OVER THIS ONE.

Taro
05-01-2012, 11:50 PM
Hello,

I'm not sure how this can be useful for the sites I'm planning to design. So a character limiter is something that limits characters. I'm guessing its for people who type too much in forms?

VIPStephan
05-02-2012, 11:50 AM
Exactly. It sets a limit of characters that can be typed into a textarea. Might be useful for guestbooks/forums/blog comment forms etc. when you want to keep posts from becoming too long.

felgall
05-02-2012, 09:34 PM
No matter what alternative you use client side you will still need to check the lengths of all input on the server and reject any that is too long.

Even where there is a way to hard code the maxlength in the HTML of your form doesn't mean that your form was used to submit the data. Someone could always make a copy of your page and remove any client side validations you build in.

VIPStephan
05-03-2012, 12:20 AM
Someone could always make a copy of your page and remove any client side validations you build in.

One can even remove elements or parts of them live, with Firebug or similar code inspection tools. I’m doing this sometimes when something like a form submission requires JS where it’s totally unnecessary (For example, one site I use sometimes requires clicking a banner link to submit form input, which opens a new window with advertising. Opening Firebug and removing the href attribute with the advertising URL from that element, I can click that banner and submit the form without worries).

felgall
05-03-2012, 04:13 AM
One can even remove elements or parts of them live, with Firebug or similar code inspection tools.

All browsers except Firefox have a built in JavaScript debugger for that purpose (the Venkmann extension provides a debugger for Firefox that works the same as the one built into all the other browsers - the Firebug extension works a bit differently and doesn't provide as much flexibility for JavaScript debugging).

rnd me
05-04-2012, 12:37 AM
All browsers except Firefox have a built in JavaScript debugger for that purpose (the Venkmann extension provides a debugger for Firefox that works the same as the one built into all the other browsers - the Firebug extension works a bit differently and doesn't provide as much flexibility for JavaScript debugging).

Venkmann, haven't seen that name in a while. I'm under the impression that all other browser's debug tools are knockoff attempts of firebug. just about anything those tools has, firebug has as well.

what does venkmann to that firebug doesn't?

felgall
05-04-2012, 01:30 AM
Venkmann, haven't seen that name in a while. I'm under the impression that all other browser's debug tools are knockoff attempts of firebug. just about anything those tools has, firebug has as well.

what does venkmann to that firebug doesn't?

The actual JavaScript debugger in all the different browsers looks to me to be just about identical to the Venkmann one.

Firebug has lots of options for debugging HTML and CSS, I haven't looked all that closely at the script part of firebug but judging by the way that almost everything in Firefox tools is a copy of the features built into a prior version of Opera it wouldn't surprise me if the Firebug script debugger was also identical in functionality to all the others - just needing extra steps to access it.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum