Max length of textarea is not working on IE8 - javascript

From research on internet, max length attribute is not working on IE 8 and 9
To resolve the problem I tried a solution from here , it use with the other function which is for presentation textarea:
//Dynamic append the textarea row
function do_resize(textArea) {
while (
textArea.rows > 1 &&
textArea.scrollHeight < textArea.offsetHeight
)
{
textArea.rows--;
}
while (textArea.scrollHeight > textArea.offsetHeight)
{
textArea.rows++;
}
textArea.rows++
}
<textarea name="q<%=countNo%>_ans" rows="3" cols="55" maxlength="2000" style="resize: none;" onkeyup="new do_resize(this);" onKeyPress="return ( this.value.length < 2000);"></textarea>
The problem is , The textarea is not able to input any character after it exceed the 2000 in IE8 9 , but I can still use the copy and paste function which will exceed the textarea limit. How to fix this? thanks

The code in the question effectively disables typing from keyboard when the limit has been reached. To impose the restriction on pasted content too, you need to handle other events, too. The following code truncates the textarea content to the given length. This is not good usability (you should probably signal an attempt to exceed the limit, instead of silent truncation, and you could have a character counter on the page to help the user), but it does what was asked for:
<textarea maxlength=2000
onchange="testLength(this)"
onkeyup="testLength(this)"
onpaste="testLength(this)"
></textarea>
<script>
var maxLength = 2000;
function testLength(ta) {
if(ta.value.length > maxLength) {
ta.value = ta.value.substring(0, maxLength);
}
}
</script>

Just for some hstory on this, maxlength on a textarea is a new HTML5 feature which was only first supported by IE in 10. IE 9 and below never supported it.

Use this code it will work for below IE 9 version. only change version in if condtion.
if(navigator.appVersion.indexOf("MSIE .9")!=-1)
{
$('#inputid').bind('keyup blur', function () {
var $this = $(this);
var len = $this.val().length;
var maxlength = 3;
if (maxlength && len > maxlength) {
var inputvalue= $this.val().slice(0, maxlength);
$this.val("");
$this.val(inputvalue);
}
});
}

Simply add onpaste fixed the problem
<textarea name="q<%=countNo%>_ans" rows="3" cols="55" maxlength="2000" style="resize: none;" onkeyup="new do_resize(this);" onKeyPress="return ( this.value.length < 2000); onpaste="return ( this.value.length < 2000);"></textarea>

Related

jQuery update character counter after pasting in more characters than maxlength

I have a form that with a textarea and I'm trying to prevent users from pasting more than 1000 characters into it. I have a div that displays the number of characters left as the user types, which is the problem. I have the pasting part working, but I'm also trying to set the character counter at the same time.
Here's the code:
<textarea name="Note" id="Note" cols="80" rows="5" class="text-input shadow form-control" maxlength="1000"></textarea>
<div id="NoteLength"></div>
<div>characters remaining.</div>
and the jQuery:
$("#NoteLength").text("1000");
//user is typing
$("#Note").keyup(function () {
el = $(this);
if (el.val().length >= 1000) {
el.val(el.val().substr(0, 1000));
} else {
$("#NoteLength").text(1000 - el.val().length);
}
});
//user is pasting
$("#Note").blur(function (event) {
var maxLength = 1000;
var length = this.value.length;
if (length > maxLength) {
$("#NoteLength").text("0");
this.value = this.value.substring(0, maxLength);
}
});
It's truncating the text as expected, but it's not resetting the NoteLength div to if I paste a large chunk of text, say 1500 characters. If I paste blocks of 200 characters, the counter works fine. Works if I backspace over the last character pasted in too, just not when I go way over in one paste which is unfortunately the most likely user scenario.
You can use the input event to capture any change to the value of the input by a user
$("#NoteLength").text("1000");
//user is changing the input value, typing or pasting, all of it
$("#Note").on('input', function () {
if (this.value.length > 1000) {
this.value = this.value.substr(0, 1000);
}
$("#NoteLength").text(1000 - this.value.length);
});

Enforcing the maxlength attribute on mobile browsers

I have an a text input with a maximum length:
<input type="text" name="name" maxlength="50">
This has been working fine on all the desktop browsers I've tried, but the maximum length does not seem to be enforced on mobile browsers.
Is there any way to get mobile browsers to enforce maxlength? I am open to using JavaScript and/or jQuery in the solution.
Try this one:
var $input = $('input')
$input.keyup(function(e) {
var max = 5;
if ($input.val().length > max) {
$input.val($input.val().substr(0, max));
}
});
jsFiddle here: http://jsfiddle.net/fttk2/1/
This problem is because predictive text is enabled on your keyboard, disable it and try again
var max = 1
input.addEventListener('keyup', function (event) {
event.target.value = event.target.value.substring(0, max)
})
I'd suggest something a bit more simple. The aboves didn't work for me unless there was a space added for the field to pick up on it... or if I hit submit right after, it still passed the information.
if($(".input") > 20){$(".input") = input.slice(0,20)};
Universal jQuery way to enforce the stated maxlength of a form field. (I needed it for sessionStorage, localStorage, and param overrides.) Code optimized for readability.
$('input').on('change', function () {
var max = $(this).attr('maxlength'),
val = $(this).val(),
trimmed;
if (max && val) {
trimmed = val.substr(0, max);
$(this).val(trimmed);
}
});
This problem is because predictive text is enabled on your mobile keyboard so disable predictive text.
<input autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" type="text" name="name" maxlength="50">
var maxLength = 10;
var field = $('#myinput');
field.keydown( function(e)
{
if ( $(this).val().length >= maxLength ) e.preventDefault();
});

Can input be limited to html <textarea>? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the best way to emulate an HTML input “maxlength” attribute on an HTML textarea?
My question is can a <textarea > be configured only to accept a certain number of characters? I can do this in the following JavaScript, but the person for whom I am designing this page does not want a status field.
My current way of doing things is I have a <textarea > that is part of a form that uses a nice JavaScript function to fill a message in a status box.
I also read SO and found Alerts and sounds really aren't the way to alert people, so the following code changes background color (and restores when appropriate) when there is an error.
Here is that code:
// Checks Form element TransDesc for overruns past 255 characters.
function warnOverDescLen()
{
var misc_text =
document.forms["InvGenPayTickets"]["TransDesc"].value;
var alert_text =
"You cannot enter more than 255 characters. Please remove some information.";
var rc = true;
if(255 < misc_text.length)
{
document.forms["InvGenPayTickets"]["trans_status"].value
= alert_text;
misc_text = misc_text.substring(0, 253);
document.forms["InvGenPayTickets"]["TransDesc"].value
= misc_text;
document.forms["InvGenPayTickets"]["trans_status"].style.backgroundColor
= "pink";
}
else
{
document.forms["InvGenPayTickets"]["trans_status"].value
= "";
document.forms["InvGenPayTickets"]["trans_status"].style.backgroundColor
= "lightgoldenrodyellow";
}
return rc;
}
<textarea rows="4" cols="60" name="TransDesc" id="TransDesc"
onkeypress="return warnOverDescLen();" ></textarea>
<span style="color: #50081E; font-weight: bold">Status</span>
<br />
<input type=text name="trans_status" id="trans_status" maxwidth="50"
size="65" />
This is a solution for HTML5, not supported by IE9 or earlier (according to this):
<textarea maxlength="255"></textarea>
Since you probably can't drop support for IE9 (and maybe even IE8), it's recommended you couple that with JavaScript, preventing the default behavior for the keydown and paste events on the textarea, as standup75 suggested.
Here is how to do that with plain JavaScript:
<textarea id="txtarea" maxlength="255"></textarea>
<script>
var field = document.getElementById('txtarea');
if(field.addEventListener) {
field.addEventListener('keydown', enforceMaxlength);
field.addEventListener('paste', enforceMaxlength);
} else {
// IE6-8
field.attachEvent('onkeydown', enforceMaxlength);
field.attachEvent('onpaste', enforceMaxlength);
}
function enforceMaxlength(evt) {
var maxLength = 255;
if(this.value.length >= maxLength) {
evt.preventDefault()
}
}
</script>
http://jsfiddle.net/snJwn/
HTML5 offers the maxLength attribute. Otherwise, you'd need some javascript, in jQuery, you'd do something like
maxLength = 50;
$("textarea").on("keydown paste", function(e){
if ($(this).val().length>=maxLength) e.preventDefault();
});
you can use the maxlength="255" (it specifies the maximum number of characters allowed in the element.)
or you can also do this by the jquery here i found the tutorial
html
<textarea cols="30" rows="5" maxlength="10"></textarea>
jquery
jQuery(function($) {
// ignore these keys
var ignore = [8,9,13,33,34,35,36,37,38,39,40,46];
// use keypress instead of keydown as that's the only
// place keystrokes could be canceled in Opera
var eventName = 'keypress';
// handle textareas with maxlength attribute
$('textarea[maxlength]')
// this is where the magic happens
.live(eventName, function(event) {
var self = $(this),
maxlength = self.attr('maxlength'),
code = $.data(this, 'keycode');
// check if maxlength has a value.
// The value must be greater than 0
if (maxlength && maxlength > 0) {
// continue with this keystroke if maxlength
// not reached or one of the ignored keys were pressed.
return ( self.val().length < maxlength
|| $.inArray(code, ignore) !== -1 );
}
})
// store keyCode from keydown event for later use
.live('keydown', function(event) {
$.data(this, 'keycode', event.keyCode || event.which);
});
});
Live example

Limiting number of characters in text area?

I'm having a text area, and I want to limit each line in the text area to have a limit of 20 characters, any solution?
Unfortunately, this is not easy to do in JavaScript unless you need to support only a small number of browsers (like one). The complication is that when determining if a new key press event should actually result in the printable character getting appended you must know if the cursor position in the textarea is in a line which cannot accept any new characters. The catch is that different browsers have different methods for determining the cursor location in a textarea.
If would suggest using jQuery and the fieldSelection plugin and setting the event handler for the textarea in question as follows:
var maxChars = 20;
var textarea = document.form1.textarea;
textarea.onkeypress = function(ev) {
// Trim any lines with length > maxChars.
var lines = textarea.value.split(/\r?\n/);
for (var i=0; i<lines.length; i++) {
if (lines[i].length >= maxChars) {
lines[i] = lines[i].substr(0, maxChars);
}
}
textarea.value = lines.join("\n");
// Determine if the keypress event should succeed.
var keyPressZeroWidth = (ev.keyCode == 13) || //...
var keyPressWouldMakeLineTooLong = // fieldSelection usage here...
return keyPressZeroWidth || !keyPressWouldMakeLineTooLong;
};
Use cols attribute in textarea
<textarea name=myText wrap=physical cols=20 rows=4></textarea>
Update:
<SCRIPT LANGUAGE="JavaScript">
function textCounter(field,maxlimit) {
if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
}
</script>
<body>
<textarea name=message wrap=physical cols=20 rows=4 onKeyDown="textCounter(this.form.message,125);" onKeyUp="textCounter(this.form.message,125);"></textarea>
</body>

How can I block further input in textarea using maxlength

I have a textarea that I want to block input on if the entered characters reaches a max-length.
I currently have a Jquery script for the textbox that calculates the characters entered and want to add something that will block input in the textarea once 150 characters are entered.
I have tried using max-length plugins in conjunction with my script but they don't seem to work. Help is appreciated.
CURRENT CODE
(function($) {
$.fn.charCount = function(options){
// default configuration properties
var defaults = {
allowed: 150,
warning: 25,
css: 'counter',
counterElement: 'span',
cssWarning: 'warning',
cssExceeded: 'exceeded',
counterText: '',
container: undefined // New option, accepts a selector string
};
var options = $.extend(defaults, options);
function calculate(obj,$cont) {
// $cont is the container, now passed in instead.
var count = $(obj).val().length;
var available = options.allowed - count;
if(available <= options.warning && available >= 0){
$cont.addClass(options.cssWarning);
} else {
$cont.removeClass(options.cssWarning);
}
if(available < 0){
$cont.addClass(options.cssExceeded);
} else {
$cont.removeClass(options.cssExceeded);
}
$cont.html(options.counterText + available);
};
this.each(function() {
// $container is the passed selector, or create the default container
var $container = (options.container)
? $(options.container)
.text(options.counterText)
.addClass(options.css)
: $('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>').insertAfter(this);
calculate(this,$container);
$(this).keyup(function(){calculate(this,$container)});
$(this).change(function(){calculate(this,$container)});
});
};
})(jQuery);
Have you tried ​the maxlength attribute? That will block input once the character limit is reached.
<textarea maxlength='150'></textarea>​​​​​​​​​​​​​​​​​​​​​​​​​​ // Won't work
<input type='text' maxlength='150' />
Edit It appears that maxlength for a textarea works in Chrome, but not in other browsers, my bad. Well, another approach would just be to monitor keydown events and if length>150, return false/preventDefault/however you want to stop the default action. You'd still want allow backspace and enter however, so monitor keycode as well.
$('#yourTextarea').keydown(function(e) {
if (this.value.length > 150)
if ( !(e.which == '46' || e.which == '8' || e.which == '13') ) // backspace/enter/del
e.preventDefault();
});
You're much better off not trying to prevent the user from typing in too many characters and instead showing a counter and only enforcing the character limit when the user tries to submit. The comment boxes Stack Overflow are a decent example. It's both easier technically and more importantly better for the user to do it this way: it's really irritating not to be able to type/paste/drag text into a textarea even if you know there's a character limit.
Textarea maxlength with Jquery works OK but probably doesn't solve the issue of pasting in larger amounts of text.
PB Edit: Has since been updated here
Try this code below i hope will work, remember to include jQuery library
<div class="texCount"></div>
<textarea class="comment"></textarea>
$(document).ready(function(){
var text_Max = 200;
$('.texCount').html(text_Max+'Words');
$('.comment').keyup(function(){
var text_Length = $('.comment').val().length;
var text_Remain = text_Max - text_Length;
$('.texCount').html(text_Remain + 'Words');
$('.comment').keydown(function(e){
if(text_Remain == 0){
e.preventDefault();
}
});
});
});
You can truncate the contents of the textarea if it is over 150 characters as described at http://web.enavu.com/daily-tip/maxlength-for-textarea-with-jquery/. I can see some issues with copy/pasting if that brings the text over the limit though.

Categories

Resources