maxlength attribute is not working in IE [duplicate] - javascript

This question already has answers here:
Maxlength for text area doesn't work in IE
(4 answers)
Closed 9 years ago.
In my js file inside a function, i m preparing like this
var x = '<span class="someclass">
<textarea class="editField" maxlength="60">
</textarea>
</span>';
here i m restricting the textarea size by using maxlength attribute,
it is not working in IE.

maxlength is not supported on <textarea> in all browsers. In any case, I don't think it's ever a good idea to actually restrain users from typing what they want. Tell them that they're over the limit, but don't lock them out.

it wouldn't. IE10 now supports the HTML5 maxlength on a textarea. see here if you need to restrict length in previous IE versions then you'll need javascript for it.

Maxlength is not supported in IE, If you want to restrict your users from entering unlimited characters in IE, you would need to use javascript for that.
You could use the below script to limit users from entering maximum characters in textarea forIE.
window.onload = function() {
var txts = document.getElementsByTagName('TEXTAREA')
for(var i = 0, l = txts.length; i < l; i++) {
if(/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) {
var func = function() {
var len = parseInt(this.getAttribute("maxlength"), 10);
if(this.value.length > len) {
alert('Maximum length exceeded: ' + len);
this.value = this.value.substr(0, len);
return false;
}
}
txts[i].onkeyup = func;
txts[i].onblur = func;
}
}
}
And Your textarea can be like:
<textarea maxlength="10"></textarea>
DEMO

The maxlength attribute is not standard for in HTML 4.01. It is defined in HTML5 though but I guess IE doesn't implement it. To make it work across all browsers you could use javascript. Here's an example.please check this it may helps you..thank you
window.onload = function() {
var txts = document.getElementsByTagName('TEXTAREA')
for(var i = 0, l = txts.length; i < l; i++) {
if(/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) {
var func = function() {
var len = parseInt(this.getAttribute("maxlength"), 10);
if(this.value.length > len) {
alert('Maximum length exceeded: ' + len);
this.value = this.value.substr(0, len);
return false;
}
}
txts[i].onkeyup = func;
txts[i].onblur = func;
}
}
}

It's actually useless to restrain the user to type on his own end. This won't make any difference unless you don't test the length of what reaches the server (you really should).
I second what Kolink said, don't try to restrain the user from typing, but you can tell him that its input won't be accepted because it's exceeding.

Related

Force first letter uppercase in input field

I'm practicing some JavaScript and would love to hear your thoughts regarding this script I wrote. I've managed to make this work. The script makes the first letter of the input value uppercase using the script below. I'm just wondering if this is a good method of doing this/if my steps are in good order just to get better
love to hear more ways of doing so, even making an option to eliminate the caps-lock via keyboard thanks,
// my input var
var strInput =document.querySelector("#inputText > input");
// my function and eventlistener
strInput.addEventListener('input',function() {
//upper case first letter with concatenate string input
var outputString = strInput.value.charAt(0).toUpperCase() + strInput.value.slice(1);
this.value = outputString;
});
As in the comments requested
Here is an example to bind the event to ALL text-inputs (except <textarea> and contenteditable="true")
var txtInputs = document.querySelectorAll("input[type='text'");
//just a simple validation if its not null, undefined or empty
if (txtInputs && txtInputs.length > 0) {
for (var i = 0; i < txtInputs.length; i++) {
var txtInput = txtInputs[i];
txtInput.addEventListener('input', function() {
var outputString = this.value.charAt(0).toUpperCase() + this.value.slice(1);
});
}

How to fix mistakes caused by wrong keyboard layout in text field

I have an app which is mostly about studying a new language. In my application there is an input field which expects text in a language that user study.
So if user focuses on that input, ideally, I want automatically to switch a layout to a target language. To make user experience more enjoyable (you don't need to worry about a wrong layout).
What I know and have tried
As I know browsers not able to provide API which I can use to determine a current layout.
I have tried to detect if the last entered character is not a typical character for the target language then I use my mapping between key codes and target language letters and replace that entered character in particular position in input. After that I get caret reset. So I return it to previous position.
The problem with the second approach that if you type fast enough you can encounter problems with a caret position. And it leads to a wrong string in the input.
Do you have any ideas how to achieve that behavior which works even when you type text with a speed when you almost immediately press two keys at the same time?
P.S. Code for that described approach
const codeToEn = {
65: 'a',
// ... and so on
}
const acceptableChars = /^[a-zA-Z0-9 .+_)(%#!?,&$*'"`~]+$/g;
document.getElementById('some-input-id').addEventListener('keyup', function (e) {
if (codeToEn[e.which]
&& !acceptableChars.test(this.value)) {
const char = codeToEn[e.which];
const {selectionStart, selectionEnd} = this;
const currentVal = this.value;
let leftPart = currentVal.substring(0, selectionStart - 1);
let rightPart = currentVal.substring(selectionStart );
this.value = leftPart + char + rightPart;
this.setSelectionRange(selectionStart, selectionEnd);
}
});
Convert Layout will help you:
https://github.com/ai/convert-layout
It really small and supports many languages.
Before you look into the code below, please note that my solution assumes that all the users use QWERTY / ЙЦУКЕН keyboard layout. This may be a huge simplification and you'll have to find a more complex approach to the keyboard layout detection (generally it's all about finding a correct symbols mapping).
The more useful part here is a fast substitution of symbols. So type fast or even copy-paste text. Hope it helps!
const En = "qwertyuiop[]asdfghjkl;'zxcvbnm,.",
Ru = "йцукенгшщзхъфывапролджэячсмитьбю";
const RuEn = [...Ru].reduce((a, e, i) => (a[e] = En[i]) && (a[e.toUpperCase()] = En[i].toUpperCase()) && a, {});
let corrected = 0;
document.getElementById('ta').addEventListener('input', function() {
let end = this.selectionEnd;
for (let i = !!corrected * (this.value.length - corrected - 1); i < end; i++) {
let s = RuEn[this.value[i]];
if (s) this.value = this.value.split(this.value[i]).join(s);
}
this.selectionEnd = end;
corrected = this.value.length - 1;
});
<textarea id="ta" cols="50" rows="10"></textarea>

AngularJS line break at points after a maximum length was reached

I'm using ng-repeat to fill a table. Some elements have a pretty long length, and I'm looking for a way to cut the content into multiple lines, if a specific length is reached.
During research I found Angulars limitTo, but it does not exactly look like I was looking for.
E.g. hi i'm a long description and oh, a package (org.foo.awesome.stuff) should convert into hi i'm a long description and oh,'
a package (org.foo.awesome.stuff)
Big thanks in advance.
Write a custom filter:
angular.module('filters', []).filter('lineBreaker', function() {
return function(input, breakLength) {
var newString = "";
for (var i = 0; i < input.length; i++) {
newString = newString+input[i];
if (i%breakLength == 0) {
newString = newString+"\n";
}
}
return newString;
};
});
Called like:
{{ expression | lineBreaker: 10 }}
I'm sure there is a more performant way to do this, but it will get the job done.
app.filter("break", function(){
return function(input, length){
return input.match(new RegExp(".{1," + length + "}", 'g')).join("<br/>");
}
});
You can use something like the following to insert a line break every limit characters:
var a = "hi i'm a long description and oh, a package (org.foo.awesome.stuff)";
var limit = 10;
for (var i = 0; i < a.length; i++) {
if (i % (limit + 1) === 0 && i > 0) {
a = [a.slice(0, i), '\n', a.slice(i)].join('');
}
}
console.log(a);
/** Output:
hi i'm a lo
ng descrip
tion and o
h, a packa
ge (org.fo
o.awesome.
stuff)"
*/
Throw that into a custom filter.
An easier solution would be to use CSS to modify the word-wrap of the text in the elements of a table.
e.g.
th {
word-wrap:normal;
}
td {
word-wrap:normal;
}
In addition to this, you would probably have to edit the width of your table elements so that word-wrapping will occur (instead of creating a box as long as your text). This can be simply achieved by editing the css styling as shown in the following code. There are two options (depending on if you want your webpage to be scaleable or not)
Option 1:
th {
width:300px;
}
...
Option 2:
td {
width:10%
}
...
Also noteable about this solution, it DOES NOT break the given string at any word (unless otherwise told to do so). You can read more about word-wrap here.

Put line break after 10 characters in text area

I have a text area that can take 10000 characters. i want to put the line breaker on each line of the text area value after 10 character
something like this i want to achive
11111111 1
111 111 11
11 11 11 1
all above line has 10 characters each.
var start = 3
var times = 1;
$('.mydesc').keyup(function () {
var len = $(this).val().length;
if (len == start) {
this.value += '\n';
times = ++times;
start= ((start * 2) + start);
}
});
but doesn't work ..
Simplest solution is to always re-add all of the new-lines:
$('.mydesc').keyup(function () {
this.value = this.value
.replace(/[\n\r]+/g, "")
.replace(/(.{10})/g, "$1\n");
});
http://jsfiddle.net/s4cUz/
Something like this would do it:
http://jsfiddle.net/Zxuj7/
$('#test_textarea').keyup(function () {
var new_stuff = $(this).val();
new_stuff = new_stuff.replace(/[\n\r]+/g,""); // clean out newlines, so we dont get dups!
var test = new_stuff.replace(/(.{10})/g,"$1\n");
$(this).val(test);
});
However, be aware that it doesn't work that well with the "deleting" of characters. If you give it a go, you will notice that when you actually delete a character and the code runs, it will put you at the end of the textarea again (because its "overwriting" the value)
UPDATE:
You may actually be better formatting AFTER they have finished editing the textarea - i.e using blur();
$('#test_textarea').blur(function () {
// leaving the field... so lets try and format nicely now
var new_stuff = $(this).val();
new_stuff = new_stuff.replace(/[\n\r]+/g,""); // clean out newlines, so we dont get dups!
new_stuff = new_stuff.replace(/(.{10})/g,"$1\n");
$(this).val(new_stuff);
});
Although that doesn't do it in real time - it does work better when deleting/editing the contents
Enhanced version of Andrew Newby's script:
$('#test_textarea').keyup(function (e) {
if (e.keyCode === 8) return; // Backspace
var new_stuff = $(this).val();
new_stuff = new_stuff.replace(/[\n\r]+/g,""); // clean out newlines, so we dont get dups!
new_stuff = new_stuff.replace(/(.{10})/g,"$1\n");
$(this).val(new_stuff);
});
This actually ignores backspace key, so at least that interaction is preserved.

javascript - maxLength in IE8

Using a javascript function to prevent exceeding the length of a textfield, but to still allow pasting & editing within it. Needs to work in IE8 & Firefox.
$(function() {
var helper = document.createElement('textarea');
//if (!('maxLength' in helper)) {
var supportsInput = 'oninput' in helper,
ev = supportsInput ? 'input' : 'propertychange paste keyup',
handler = function() {
var maxlength = +$(this).attr('maxlength');
if (this.value.length > maxlength) {
this.value = this.value.substring(0, maxlength);
}
};
$('textarea[maxlength]').on(ev, supportsInput ? handler : function() {
var that = this;
setTimeout(function() {
handler.call(that);
}, 0);
});
//}
});
It works okay if the text is on one line (testing with maxLength = 25). However, it doesn't do carriage returns & line feeds or account for them properly.
For example, if I enter the following text on one line:
1111122222333334444455555
it uses all 25 characters.
However, if I enter text on each line & hit enter, this is what I am able to enter:
11111
22222
33333
4444
Which is only 22 characters. I know that it is detecting a carriage return, because when I put in:
11111
a character counter shows 5. When I hit the enter key, the counter goes to 6, if I enter 22222 the counter is now 11.
The code I'm using to count the characters is:
$("#myTextArea").keyup(function() {
var j = $(this).val().length;
var i = 25 - j;
$("#charsUsed").text( j );
$("#charsLeft").text( i );
});
I thought the issue might be some code I put in to resize the TextArea automatically, but it isn't. I'm sure I am just missing something on the code & would appreciate input on what I'm doing wrong & haven't seem to have figured out yet.
I stumbled upon the answer myself. It turns out the character counter I was using was not accurately counting the line breaks in the <textarea>.
Although I was using IE8, I found the answer in a question about Chrome counting characters wrong in textarea with maxLength attribute. That question is here.
The code I used before:
$("#myTextArea").keyup(function() {
var j = $(this).val().length;
var i = 25 - j;
$("#charsUsed").text( j );
$("#charsLeft").text( i );
});
has been modified to:
$("#myTextArea").keyup(function() {
var x = $("#myTextArea").val();
var newLines = x.match(/(\r\n|\n|\r)/g);
var addition = 0;
if (newLines != null) {
addition = newLines.length;
}
var j = x.length + addition;
var i = 25 - j;
$("#charsUsed").text( j );
$("#charsLeft").text( i );
});
The embedded new lines must be transmitted as a CR LF pair - actually 2 characters. Thanks to the posters in the other thread for their help.

Categories