Max length for HTML <textarea> - javascript

How to restrict the maximum number of characters that can be entered into an HTML <textarea>? I'm looking for a cross-browser solution.

The TEXTAREA tag does not have a MAXLENGTH attribute the way that an
INPUT tag does, at least not in most standard browsers. A very simple and effective way to limit the number of characters that can be typed into a TEXTAREA tag is:
<textarea onKeyPress="return ( this.value.length < 50 );"></textarea>
Note: onKeyPress, is going to prevent any button press, any button including the backspace key.
This works because the Boolean expression compares the field's length
before the new character is added to the maximum length you want (50 in this example, use your own here), and returns true if there is room for one more, false if not. Returning false from most events cancels the default action.
So if the current length is already 50 (or more), the handler returns false,
the KeyPress action is cancelled, and the character is not added.
One fly in the ointment is the possibility of pasting into a TEXTAREA,
which does not cause the KeyPress event to fire, circumventing this check.
Internet Explorer 5+ contains an onPaste event whose handler can contain the
check. However, note that you must also take into account how many
characters are waiting in the clipboard to know if the total is going to
take you over the limit or not. Fortunately, IE also contains a clipboard
object from the window object.1 Thus:
<textarea onKeyPress="return ( this.value.length < 50 );"
onPaste="return (( this.value.length +
window.clipboardData.getData('Text').length) < 50 );"></textarea>
Again, the onPaste event and clipboardData object are IE 5+ only. For a cross-browser solution, you will just have to use an OnChange or OnBlur handler to check the length, and handle it however you want (truncate the value silently, notify the user, etc.). Unfortunately, this doesn't catch the error as it's happening, only when the user attempts to leave the field, which is not quite as friendly.
Source
Also, there is another way here, including a finished script you could include in your page:
http://cf-bill.blogspot.com/2005/05/textarea-maxlength-revisited.html

HTML5 now allows maxlength attribute on <textarea>.
It is supported by all browsers except IE <= 9 and iOS Safari 8.4. See support table on caniuse.com.

$(function(){
$("#id").keypress(function() {
var maxlen = 100;
if ($(this).val().length > maxlen) {
return false;
}
})
});
Reference Set maxlength in Html Textarea

Related

Allow Copy/Paste in a disabled input text box in Firefox browsers

I have a input text box disabled:
<input type="text" name="name" disabled="disabled" />
In IE and in Chrome you can copy and paste the value populated in that input field but in Firefox you cannot.
Firefox does not allow clipboard manipulation through JavaScript for valid security concerns.
Any suggestion? Is there a work around this?
readonly="readonly" will do the job
it should be supported by the major browsers
I don't like using readonly="readonly", ever. It leaves the field focusable and reachable via tab keypress and, if, god forbid, the user hits the backspace key while the read-only field is focused, then most browsers treat it like the user hit the 'back' button and bring up the previously viewed page. Not what you want to see happen when you're filling out a large form, especially if you are using some archaic browser that doesn't preserve the form data when you hit the 'next' button to return to it. Also very, very bad when using some single-page web application, where 'back' takes you to a whole other world, and 'next' doesn't even restore your form, much less its data.
I've worked around this by rendering DIVs instead of input fields when I need the field disabled (or PRE instead of a textarea). Not always easy to do dynamically but I've managed to make fairly short work of it with AngularJS templates.
If you have time, head over to the Mozilla Bugzilla and ask them to fix it.
tl;dr: Support for selecting and copying text in a disabled field is unreliable; use the readonly attribute or a non-input element, such as a <span> instead, if this functionality is necessary. Use JavaScript to modify the behavior of the readonly input to prevent unwanted behavior such as going back a page when someone hits the backspace key while the readonly input has focus.
*UPDATE: 2018.12.24
The spec has changed since this answer was originally posted (thanks to Wrightboy for pointing this out); it now includes the following caveat with regards to disabled fields:
Any other behavior related to user interaction with disabled controls, such as whether text can be selected or copied, is not defined in this standard.
— https://html.spec.whatwg.org/multipage/input.html#the-readonly-attribute
Disabled fields still cannot receive focus nor click events.
Because the standard does not define whether or not text within disabled controls can be selected or copied and because at least one major browser doesn't support that functionality, it's probably best to avoid relying on that behavior.
Original Answer
This is the expected behavior for a disabled field (as of the original date of this answer). IE and Chrome are being generous, but Firefox is behaving appropriately.
If you want to prevent the user from changing the value of the field, but you still want them to be able to read it, and/or copy it's value, then you should use the readonly attribute. This will allow them to set focus to the element (necessary for copying), and also access the field via the tab button.
If you are concerned about a user accidentally hitting the backspace button inside the readonly field and causing the browser to navigate back a page, you can use the following code to prevent that behavior:
document.addEventListener("DOMContentLoaded", function() {
var inputs = document.querySelectorAll('[readonly]');
for(var i=0; i < inputs.length; i++){
inputs[i].addEventListener('keydown', function(e){
var key = e.which || e.keyCode || 0;
if(key === 8){
e.preventDefault();
}
})
}
});
<input value="Hello World" readonly=readonly />
As quick answer, one can have another not disabled element to enable + copy/paste + redisable your input text, like this:
$('#btnCopy').click(function(){
$('#txtInputDisabled').removeAttr('disabled');
$('#txtInputDisabled').select();
document.execCommand("copy");
$('#txtInputDisabled').attr('disabled','disabled');
});
You can se my complete response to this post
Refer to my post to the same question. It does the following:
Makes the textbox just like readonly without using the readonly attribute on the input tag, but will honor tab index and set focus
Supports all clipboard functions win and mac with mouse or keyboard
Allows undo, redo and select all
Restrict HTML input to only allow paste
You can accomplish this in share point by utilizing the contenteditable attribute as follows with jquery.
$("#fieldID").attr("contenteditable", "false");
This will allow the user to highlight the text and copy it but will not allow them to enter anything in the field.

Howto cancel the effects of the Escape button on an html input?

I'm building a JavaScript game where audio plays and based on the audio you're supposed to type some text into a big textbox. JavaScript is used to score your answer and then clear the textbox to prepare for the next audio clip.
The problem: In some cases when pressing the esc (escape) key while focused within an empty <input type="text" />, the textbox gets populated with some old text.
I'm using MooTools and have tried using event.stop() (which stops propagating and also executes preventDefault) within keypress, keydown, and keyup with no luck.
How can I prevent the [esc] button from changing the value within a textbox?
(This is important because I'm using the [esc] key as a keyboard shortcut to replay the audio)
I was able to fix this by just calling blur() and then focus() on the input box. That cleared the problem in Firefox for me at least.
Interesting problem - it happens in IE for example but not Chrome. Here is a solution I have tested in Chrome and IE (it seems to work).
Expanded version:
Script in page header:
<script>
var buff; //Must have global scope
var input = document.getElementById("testinput"); //Defined here to save cpu (instead of on every key press).
function CheckPreBuff(e)
{
var ev = window.event ? event : e; //Get the event object for IE or FF
var unicode = (typeof(ev.keyCode) != "undefined")? ev.keyCode : ev.charCode;
if(unicode != 27) buff = input.value; //The 'escape' key has a unicode value of 27
else input.value = buff; //Only set the input contents when needed, so not to waste cpu.
}
</script>
Where 'testinput' is the input we are disabling escape on. The testinput html is below:
<input id="testinput" onkeypress="CheckPreBuff();" onkeyup="CheckPreBuff();" type="text"/>
Notice both 'onkeyup' and 'onkeypress' were used - technically only 'onkeyup' is needed, although using 'onkeypress' prevents the text box going blank momentarily whilst the escape key is depressed.
Manually minified + error prevention + multiple inputs supported (if you prefer)
Script in header:
<script>
var buff = [];
function InitCPB(obj){if(typeof(obj)=="undefined")return;buff[0]=obj;buff[1]="";obj.onkeypress=CPB;obj.onkeyup=CPB;}
function CPB(e){if(typeof((buff[0]))=="undefined")return;var ev=window.event?event:e;(((typeof(ev.keyCode)!="undefined")?ev.keyCode:ev.charCode)!=27)?buff[1]=(buff[0]).value:(buff[0]).value=buff[1];}
</script>
testinput html tag (although an id is no longer needed):
<input onfocus="InitCPB(this);" type="text"/>
Both methods keep a copy of what the text inputs contained before the next key was pressed, if the key pressed was 'escape', unicode 27, then the previous text entry was put back into the text box (this is discriminatory so the script does not add too much load to the browser on every key press).
The second version allows for multiple text inputs on the same page having the escape key disabled - just so long as they have the onFocus attribute set as above (the multiple elements will not interfere with each other). It also checks the objects being passes to it are defined, to prevent accidental mis-implementation giving IE a heart attack!
I hope this helps.
When escape detected do what is needed to be done and at the end return false;
It solved the problem in firefox 25 for me.

jQuery - set max length for textarea

I want to have a textarea with a maximum length, and show the user how many characters are left (as it's done on twitter), but I can't seem to get it to be as good.
The requirements are:
Must show the current number of characters they've typed
Must remain accurate when a key is held down
Must remain accurate when backspace/delete is used
Must remain accurate when text in the box is selected and cut/delete by using the right click menu
Must allow the user to go over the limit (I hate it when a field actually prevents me from going over, it makes it harder to edit it down)
Is there a jQuery plugin to do this? Or is there a simple javascript way of doing it (the onChange method doesn't update as they're typing, and keydown/keyup would have troubles with mouse changes)
At the moment it seems like the best way is to have a function to do what I want (check the length and update the message), call it with keydown/keyup/change, and also poll it a few times per second. Is there a better way?
What you usually do is attach multiple event handlers pointing to a validating function, but you won't be able to stop the rightclick/paste with this...
$(document).ready(function() {
$("#myTextArea").live("change keydown keyup keypress", function() {
validate();
});
});
function validate() {
// validates #myTextArea
}
try this
$("#textarea").on('input',function(){
if(this.value.length > 50) {
alert("u cant input more.");
this.value = this.value.substring(0,50);
}
$('#counter').html(this.value.length + '/50');
});
maybe this code help u

Possible to stop copy + pasting into a html textbox?

Got a password field, and ideally we want people to type their password rather than copy and paste it in. Is there an easy way using Javascript?
Not consistently across all browsers. Most browsers (not Opera, Firefox 2) support the cancellable onpaste event:
document.getElementById("password").onpaste = function () {
return false;
}
https://developer.mozilla.org/en/DOM/element.onpaste
First things first: this a bad idea.
You could use the key press events on the password field to detect what key was pressed, to check whether the change in the password field matches the event (if they press "a", then check if the letter "a" was indeed inserted), and restore the previous value (with an error message) if it does not.
Of course, people will just have their web browser remember their password for them.
Some banks replace the password field with an image of digits where you have to click to enter the password (here, for instance). You could use JavaScript to replace the password field with that image when JavaScript is enabled.
$(':password').bind('paste', function(e) {
return false;
})
You can measure the time it takes from the first to the last change. If it was too short, clear the field...
You can do this with the help of Polling Technique. Hoewver this is not the suggested way for textboxes. If you have observed some of the Bank site allows you to enter password via a keypad (with mouse clicks). And password field is disabled for keyboard entry

How to get a Javascript routine to NOT act if it's in a text box?

I've got a simple page, and in that page runs a simple jquery keypress routine to catch clicks of the numbers 1 to 9 (has to be that to pass RNIB accessibility test).
And in that page is a form, which can have numbers entered as part of a postcode.
http://find.talking-newspapers.co.uk/result.php?addressInput=kingston
Scroll to the bottom, try typing 8 or 9 for example. The text is entered, but it also acts on the keypress. Expected, but not good.
I'm aware of various things like document.getElementById, but I can't figure out how to put these together to ensure that while the cursor is in the text input box, it doesn't act out the keypress catcher.
The target property of the event object (the parameter to the handler function) will tell you which element actually generated the event.
You need to check whether e.target is an <input> element, like this:
if ($(e.target).is(':input'))
return;

Categories

Resources