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

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

Related

Javascript how to place cursor at end of input field text after inserting text? [duplicate]

What is the best way (and I presume simplest way) to place the cursor at the end of the text in a input text element via JavaScript - after focus has been set to the element?
There's a simple way to get it working in most browsers.
this.selectionStart = this.selectionEnd = this.value.length;
However, due to the *quirks of a few browsers, a more inclusive answer looks more like this
setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
Using jQuery (to set the listener, but it's not necessary otherwise)
$('#el').focus(function(){
var that = this;
setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='el' type='text' value='put cursor at end'>
Using Vanilla JS (borrowing addEvent function from this answer)
// Basic cross browser addEvent
function addEvent(elem, event, fn){
if(elem.addEventListener){
elem.addEventListener(event, fn, false);
}else{
elem.attachEvent("on" + event,
function(){ return(fn.call(elem, window.event)); });
}}
var element = document.getElementById('el');
addEvent(element,'focus',function(){
var that = this;
setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
});
<input id='el' type='text' value='put cursor at end'>
Quirks
Chrome has an odd quirk where the focus event fires before the cursor is moved into the field; which screws my simple solution up. Two options to fix this:
You can add a timeout of 0 ms (to defer the operation until the stack is clear)
You can change the event from focus to mouseup. This would be pretty annoying for the user unless you still kept track of focus. I'm not really in love with either of these options.
Also, #vladkras pointed out that some older versions of Opera incorrectly calculate the length when it has spaces. For this you can use a huge number that should be larger than your string.
Try this, it has worked for me:
//input is the input element
input.focus(); //sets focus to element
var val = this.input.value; //store the value of the element
this.input.value = ''; //clear the value of the element
this.input.value = val; //set that value back.
For the cursor to be move to the end, the input has to have focus first, then when the value is changed it will goto the end. If you set .value to the same, it won't change in chrome.
I faced this same issue (after setting focus through RJS/prototype) in IE.
Firefox was already leaving the cursor at the end when there is already a value for the field. IE was forcing the cursor to the beginning of the text.
The solution I arrived at is as follows:
<input id="search" type="text" value="mycurrtext" size="30"
onfocus="this.value = this.value;" name="search"/>
This works in both IE7 and FF3 but doesn't work in modern browsers (see comments) as it is not specified that UA must overwrite the value in this case (edited in accordance with meta policy).
After hacking around with this a bit, I found the best way was to use the setSelectionRange function if the browser supports it; if not, revert to using the method in Mike Berrow's answer (i.e. replace the value with itself).
I'm also setting scrollTop to a high value in case we're in a vertically-scrollable textarea. (Using an arbitrary high value seems more reliable than $(this).height() in Firefox and Chrome.)
I've made it is as a jQuery plugin. (If you're not using jQuery I trust you can still get the gist easily enough.)
I've tested in IE6, IE7, IE8, Firefox 3.5.5, Google Chrome 3.0, Safari 4.0.4, Opera 10.00.
It's available on jquery.com as the PutCursorAtEnd plugin. For your convenience, the code for release 1.0 is as follows:
// jQuery plugin: PutCursorAtEnd 1.0
// http://plugins.jquery.com/project/PutCursorAtEnd
// by teedyay
//
// Puts the cursor at the end of a textbox/ textarea
// codesnippet: 691e18b1-f4f9-41b4-8fe8-bc8ee51b48d4
(function($)
{
jQuery.fn.putCursorAtEnd = function()
{
return this.each(function()
{
$(this).focus()
// If this function exists...
if (this.setSelectionRange)
{
// ... then use it
// (Doesn't work in IE)
// Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
var len = $(this).val().length * 2;
this.setSelectionRange(len, len);
}
else
{
// ... otherwise replace the contents with itself
// (Doesn't work in Google Chrome)
$(this).val($(this).val());
}
// Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Google Chrome)
this.scrollTop = 999999;
});
};
})(jQuery);
<script type="text/javascript">
function SetEnd(txt) {
if (txt.createTextRange) {
//IE
var FieldRange = txt.createTextRange();
FieldRange.moveStart('character', txt.value.length);
FieldRange.collapse();
FieldRange.select();
}
else {
//Firefox and Opera
txt.focus();
var length = txt.value.length;
txt.setSelectionRange(length, length);
}
}
</script>
This function works for me in IE9, Firefox 6.x, and Opera 11.x
It's 2019 and none of the methods above worked for me, but this one did, taken from https://css-tricks.com/snippets/javascript/move-cursor-to-end-of-input/
function moveCursorToEnd(id) {
var el = document.getElementById(id)
el.focus()
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = el.value.length;
} else if (typeof el.createTextRange != "undefined") {
var range = el.createTextRange();
range.collapse(false);
range.select();
}
}
<input id="myinput" type="text" />
Move cursor to end
I've tried the following with quite great success in chrome
$("input.focus").focus(function () {
var val = this.value,
$this = $(this);
$this.val("");
setTimeout(function () {
$this.val(val);
}, 1);
});
Quick rundown:
It takes every input field with the class focus on it, then stores the old value of the input field in a variable, afterwards it applies the empty string to the input field.
Then it waits 1 milisecond and puts in the old value again.
el.setSelectionRange(-1, -1);
https://codesandbox.io/s/peaceful-bash-x2mti
This method updates the HTMLInputElement.selectionStart, selectionEnd,
and selectionDirection properties in one call.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange
In other js methods -1 usually means (to the) last character. This is the case for this one too, but I couldn't find explicit mention of this behavior in the docs.
Simple. When editing or changing values, first put the focus then set value.
$("#catg_name").focus();
$("#catg_name").val(catg_name);
Still the intermediate variable is needed, (see var val=)
else the cursor behaves strange, we need it at the end.
<body onload="document.getElementById('userinput').focus();">
<form>
<input id="userinput" onfocus="var val=this.value; this.value=''; this.value= val;"
class=large type="text" size="10" maxlength="50" value="beans" name="myinput">
</form>
</body>
const end = input.value.length
input.setSelectionRange(end, end)
// πŸ‘‡ scroll to the bottom if a textarea has long text
input.focus()
Try this one works with Vanilla JavaScript.
<input type="text" id="yourId" onfocus="let value = this.value; this.value = null; this.value=value" name="nameYouWant" class="yourClass" value="yourValue" placeholder="yourPlaceholder...">
In Js
document.getElementById("yourId").focus()
For all browsers for all cases:
function moveCursorToEnd(el) {
window.setTimeout(function () {
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = el.value.length;
} else if (typeof el.createTextRange != "undefined") {
var range = el.createTextRange();
range.collapse(false);
range.select();
}
}, 1);
}
Timeout required if you need to move cursor from onFocus event handler
I like the accepted answer a lot, but it stopped working in Chrome. In Chrome, for the cursor to go to the end, input value needs to change. The solution is as follow:
<input id="search" type="text" value="mycurrtext" size="30"
onfocus="var value = this.value; this.value = null; this.value = value;" name="search"/>
document.querySelector('input').addEventListener('focus', e => {
const { value } = e.target;
e.target.setSelectionRange(value.length, value.length);
});
<input value="my text" />
In jQuery, that's
$(document).ready(function () {
$('input').focus(function () {
$(this).attr('value',$(this).attr('value'));
}
}
I just found that in iOS, setting textarea.textContent property will place the cursor at the end of the text in the textarea element every time. The behavior was a bug in my app, but seems to be something that you could use intentionally.
This problem is interesting. The most confusing thing about it is that no solution I found solved the problem completely.
+++++++ SOLUTION +++++++
You need a JS function, like this:
function moveCursorToEnd(obj) {
if (!(obj.updating)) {
obj.updating = true;
var oldValue = obj.value;
obj.value = '';
setTimeout(function(){ obj.value = oldValue; obj.updating = false; }, 100);
}
}
You need to call this guy in the onfocus and onclick events.
<input type="text" value="Test Field" onfocus="moveCursorToEnd(this)" onclick="moveCursorToEnd(this)">
IT WORKS ON ALL DEVICES AN BROWSERS!!!!
var valsrch = $('#search').val();
$('#search').val('').focus().val(valsrch);
Taking some of the answers .. making a single-line jquery.
$('#search').focus().val($('#search').val());
If the input field just needs a static default value I usually do this with jQuery:
$('#input').focus().val('Default value');
This seems to work in all browsers.
While this may be an old question with lots of answers, I ran across a similar issue and none of the answers were quite what I wanted and/or were poorly explained. The issue with selectionStart and selectionEnd properties is that they don't exist for input type number (while the question was asked for text type, I reckon it might help others who might have other input types that they need to focus). So if you don't know whether the input type the function will focus is a type number or not, you cannot use that solution.
The solution that works cross browser and for all input types is rather simple:
get and store the value of input in a variable
focus the input
set the value of input to the stored value
That way the cursor is at the end of the input element.
So all you'd do is something like this (using jquery, provided the element selector that one wishes to focus is accessible via 'data-focus-element' data attribute of the clicked element and the function executes after clicking on '.foo' element):
$('.foo').click(function() {
element_selector = $(this).attr('data-focus-element');
$focus = $(element_selector);
value = $focus.val();
$focus.focus();
$focus.val(value);
});
Why does this work? Simply, when the .focus() is called, the focus will be added to the beginning of the input element (which is the core problem here), ignoring the fact, that the input element already has a value in it. However, when the value of an input is changed, the cursor is automatically placed at the end of the value inside input element. So if you override the value with the same value that had been previously entered in the input, the value will look untouched, the cursor will, however, move to the end.
Super easy (you may have to focus on the input element)
inputEl = getElementById('inputId');
var temp = inputEl.value;
inputEl.value = '';
inputEl.value = temp;
Set the cursor when click on text area to the end of text...
Variation of this code is...ALSO works! for Firefox, IE, Safari, Chrome..
In server-side code:
txtAddNoteMessage.Attributes.Add("onClick", "sendCursorToEnd('" & txtAddNoteMessage.ClientID & "');")
In Javascript:
function sendCursorToEnd(obj) {
var value = $(obj).val(); //store the value of the element
var message = "";
if (value != "") {
message = value + "\n";
};
$(obj).focus().val(message);
$(obj).unbind();
}
If you set the value first and then set the focus, the cursor will always appear at the end.
$("#search-button").click(function (event) {
event.preventDefault();
$('#textbox').val('this');
$("#textbox").focus();
return false;
});
Here is the fiddle to test
https://jsfiddle.net/5on50caf/1/
I wanted to put cursor at the end of a "div" element where contenteditable = true, and I got a solution with Xeoncross code:
<input type="button" value="Paste HTML" onclick="document.getElementById('test').focus(); pasteHtmlAtCaret('<b>INSERTED</b>'); ">
<div id="test" contenteditable="true">
Here is some nice text
</div>
And this function do magic:
function pasteHtmlAtCaret(html) {
var sel, range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// non-standard and not supported in all browsers (IE9, for one)
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ( (node = el.firstChild) ) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
// IE < 9
document.selection.createRange().pasteHTML(html);
}
}
Works fine for most browsers, please check it, this code puts text and put focus at the end of the text in div element (not input element)
https://jsfiddle.net/Xeoncross/4tUDk/
Thanks, Xeoncross
I also faced same problem. Finally this gonna work for me:
jQuery.fn.putCursorAtEnd = = function() {
return this.each(function() {
// Cache references
var $el = $(this),
el = this;
// Only focus if input isn't already
if (!$el.is(":focus")) {
$el.focus();
}
// If this function exists... (IE 9+)
if (el.setSelectionRange) {
// Double the length because Opera is inconsistent about whether a carriage return is one character or two.
var len = $el.val().length * 2;
// Timeout seems to be required for Blink
setTimeout(function() {
el.setSelectionRange(len, len);
}, 1);
} else {
// As a fallback, replace the contents with itself
// Doesn't work in Chrome, but Chrome supports setSelectionRange
$el.val($el.val());
}
// Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Chrome)
this.scrollTop = 999999;
});
};
This is how we can call this:
var searchInput = $("#searchInputOrTextarea");
searchInput
.putCursorAtEnd() // should be chainable
.on("focus", function() { // could be on any event
searchInput.putCursorAtEnd()
});
It's works for me in safari, IE, Chrome, Mozilla. On mobile devices I didn't tried this.
Check this solution!
//fn setCurPosition
$.fn.setCurPosition = function(pos) {
this.focus();
this.each(function(index, elem) {
if (elem.setSelectionRange) {
elem.setSelectionRange(pos, pos);
} else if (elem.createTextRange) {
var range = elem.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
});
return this;
};
// USAGE - Set Cursor ends
$('#str1').setCurPosition($('#str1').val().length);
// USAGE - Set Cursor at 7 position
// $('#str2').setCurPosition(7);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Set cursor at any position</p>
<p><input type="text" id="str1" value="my string here" /></p>
<p><input type="text" id="str2" value="my string here" /></p>
I took the best answers from here, and created a function that works well in Chrome.
You will need to wrap the logic in a timeout, because you have to wait for the focus to finish before accessing the selection
To place the cursor at the end, the selection start needs to be placed at the end
In order to scroll to the end of the input field, the scrollLeft needs to match the scrollWidth
/**
* Upon focus, set the cursor to the end of the text input
* #param {HTMLInputElement} inputEl - An HTML <input> element
*/
const setFocusEnd = (inputEl) => {
setTimeout(() => {
const { scrollWidth, value: { length } } = inputEl;
inputEl.setSelectionRange(length, length);
inputEl.scrollLeft = scrollWidth;
}, 0);
};
document
.querySelector('input')
.addEventListener('focus', (e) => setFocusEnd(e.target));
html, body {
width: 100%;
height: 100%;
margin: 0;
}
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
input:focus {
background-color: hsla(240, 100%, 95%, 1.0);
}
<input
type="text"
placeholder="Search..."
value="This is some really, really long text">
<input id="input_1">
<input id="input_2" type="hidden">
<script type="text/javascript">
//save input_1 value to input_2
$("#input_2").val($("#input_1").val());
//empty input_1 and add the saved input_2 into input_1
$("#input_1").val("").val($("#input_2").val()).focus();
</script>

Programmatically focus on next input field in mobile safari

I have several input fields in line that acts like a crossword answer line:
Each square has its own input field. The reason for this is amongst other things that sometimes a square can be pre-populated. Now, on desktop browser the cursor jumps to the next input field whenever a char is entered. That works really well using something like:
$(this).next('input').focus();
But the problem on mobile safari (we test on ios) is that I don’t know how to automatically "jump" to the next input field programatically. The user can do it via the the "next" button, but is there a way to do this automatically?
I know that the focus() trigger has some limitations on ios, but I’ve also seen some workaround using synthesized clicks etc.
I found a workaround that might work for you.
Apparently IOS/Safari only "accepts" the focus when inside a touch event handler. I triggered a touch event and inserted the .focus() inside it. I tried this on my iPhone3S and iPhone5S with Safari and it works:
var focused = $('input:first'); //this is just to have a starting point
$('button').on('click', function () { // trigger touch on element to set focus
focused.next('input').trigger('touchstart'); // trigger touchstart
});
$('input').on('touchstart', function () {
$(this).focus(); // inside this function the focus works
focused = $(this); // to point to currently focused
});
Demo here
(press next button in demo)
Programmatically moving to the next input field in a mobile browser without dismissing the keyboard appears to be impossible. (This is terrible design, but it's what we have to work with.) However, a clever hack is to swap the input element positions, values, and attributes with Javascript so that it looks like you are moving to the next field when in fact you are still focused on the same element. Here is code for a jQuery plug-in that swaps the id, name, and value. You can adapt it to swap other attributes as necessary. Also be sure to fix up any registered event handlers.
$.fn.fakeFocusNextInput = function() {
var sel = this;
var nextel = sel.next();
var nextval = nextel.val();
var nextid = nextel.attr('id');
var nextname = nextel.attr('name');
nextel.val(sel.val());
nextel.attr('id', sel.attr('id'));
nextel.attr('name', sel.attr('name'));
sel.val(nextval);
sel.attr('id', nextid);
sel.attr('name', nextname);
// Need to remove nextel and not sel to retain focus on sel
nextel.remove();
sel.before(nextel);
// Could also return 'this' depending on how you you want the
// plug-in to work
return nextel;
};
Demo here: http://jsfiddle.net/EbU6a/194/
UIWebview has the property keyboardDisplayRequiresUserAction
When this property is set to true, the user must explicitly tap the elements in the web view to display the keyboard (or other relevant input view) for that element. When set to false, a focus event on an element causes the input view to be displayed and associated with that element automatically.
https://developer.apple.com/documentation/uikit/uiwebview/1617967-keyboarddisplayrequiresuseractio
I hope this is what you are looking for-
$(document).ready(function() {
$('input:first').focus(); //focus first input element
$('input').on('keyup', function(e) {
if(e.keyCode == 8) { //check if backspace is pressed
$(this).prev('input').focus();
return;
}
if($(this).val().length >= 1) { //for e.g. you are entering pin
if ($(this).hasClass("last")) {
alert("done");
return;
}
$(this).next('input').focus();
}
});
$('input').on('focus', function() {
if(!$(this).prev('input').val()){
$(this).prev('input').focus();
}
});
});
check code here-
https://jsbin.com/soqubal/3/edit?html,output
Add this line in your config file in ios section
preference name="KeyboardDisplayRequiresUserAction" value="false"
I encounter the same problem on safari ios. on login page, I programmatically focus on next input field after user input one sms code.
I trigger the auto focus on input change event. I fixed the problem by adding a delay.
For details, see the code below
<InputItem
value={item}
type='number'
maxLength={1}
ref={el => this[`focusInstRef${index}`] = el}
onChange={(value) => {
value&&index !== 5 && setTimeout(() => {this[`focusInstRef${index + 1}`].focus()}, 5);
vAppStore.setSmsCodeArr(value, index);}
}
/>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#hidebox {position:absolute; border: none; background:transparent;padding:1px;}
#hidebox:focus{outline: 0;}
</style>
</head>
<body>
<input type="text" maxlength="1" onkeyup="keyUp(this)" onkeydown="keyDown(this)" size="2" id="hidebox" at="1">
<input type="text" maxlength="1" size="2" id="mFirst" at="1" onfocus="onFocus(this)"><input type="text" maxlength="1" size="2" id="mSecond" at="2" onfocus="onFocus(this)"><input type="text" maxlength="1" size="2" id="mThird" at="3" onfocus="onFocus(this)"><input type="text" maxlength="1" size="2" id="mFourth" at="4" onfocus="onFocus(this)">
</li>
<script type="text/javascript">
window.onload = function() {
document.getElementById("mFirst").focus();
}
var array = ["mFirst","mSecond","mThird","mFourth"];
function keyUp(e) {
var curId = array[Number(e.getAttribute("at"))-1];
var nextId = array[Number(e.getAttribute("at"))];
var curval= e.value;
var letters = /^[0-9a-zA-Z]+$/;
if(e.value.match(letters)){
document.getElementById(curId).value = curval;
if(e.getAttribute("at") <= 3){
var nextPos = document.getElementById(nextId).offsetLeft;
e.setAttribute("at",Number(e.getAttribute("at"))+1);
e.style.left = nextPos+"px";
}
e.value = ""
}else {
e.value = "";
}
}
function keyDown(e) {
var curId = array[Number(e.getAttribute("at"))-1];
document.getElementById(curId).value = "";
}
function onFocus(e) {
document.getElementById("hidebox").focus();
document.getElementById("hidebox").setAttribute("at",Number(e.getAttribute("at")));
document.getElementById("hidebox").style.left = e.offsetLeft+"px";
document.getElementById("hidebox").style.top = e.offsetTop+"px";
}
</script>
</body>
</html>

Max length of textarea is not working on IE8

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>

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